diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor.meta new file mode 100644 index 00000000..9ca6c08e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6deb0dcf8adbd4f8f92d5482999b05bf +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime.meta new file mode 100644 index 00000000..de034322 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e8ba5b17cffbb4ffea892f674fc8629f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/CheckUnityVersion.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/CheckUnityVersion.cs new file mode 100644 index 00000000..34f112cc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/CheckUnityVersion.cs @@ -0,0 +1,16 @@ +using System; +using UnityEditor; + +namespace Fantasy +{ + internal static class CheckUnityVersion + { + [InitializeOnLoadMethod] + private static void OnInitializeOnLoad() + { +#if !UNITY_2021_3_OR_NEWER + Debug.LogError("Fantasy支持的最低版本为Unity2021.3.14f1c1"); +#endif + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/CheckUnityVersion.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/CheckUnityVersion.cs.meta new file mode 100644 index 00000000..1f13ace4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/CheckUnityVersion.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 455f338921e74471841971fd6b79db01 +timeCreated: 1725943424 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Fantasy.Editor.asmdef b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Fantasy.Editor.asmdef new file mode 100644 index 00000000..b6ddabbb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Fantasy.Editor.asmdef @@ -0,0 +1,18 @@ +{ + "name": "Fantasy.Editor", + "rootNamespace": "", + "references": [ + "GUID:0b7224b83ba514121aa026f3857f820a" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Fantasy.Editor.asmdef.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Fantasy.Editor.asmdef.meta new file mode 100644 index 00000000..d5a4e8b1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Fantasy.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 36410968656dd49358af485aad0b0c4c +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/FantasyStartup.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/FantasyStartup.cs new file mode 100644 index 00000000..c541657e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/FantasyStartup.cs @@ -0,0 +1,49 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Fantasy +{ + [InitializeOnLoad] + public static class FantasyStartup + { + private const string ScriptAssemblies = "Library/ScriptAssemblies/"; + + static FantasyStartup() + { + if (!FantasySettingsScriptableObject.Instance.autoCopyAssembly) + { + return; + } + + var hotUpdatePath = FantasySettingsScriptableObject.Instance.hotUpdatePath; + + if (string.IsNullOrEmpty(hotUpdatePath)) + { + Debug.LogError("请先在菜单Fantasy-Fantasy Settings里设置HotUpdatePath目录位置"); + return; + } + + if (!Directory.Exists(hotUpdatePath)) + { + Directory.CreateDirectory(hotUpdatePath); + } + + // ReSharper disable once StringLastIndexOfIsCultureSpecific.1 + if (hotUpdatePath.LastIndexOf("/") != hotUpdatePath.Length - 1) + { + FantasySettingsScriptableObject.Instance.hotUpdatePath += "/"; + hotUpdatePath = FantasySettingsScriptableObject.Instance.hotUpdatePath; + } + + foreach (var instanceHotUpdateAssemblyDefinition in FantasySettingsScriptableObject.Instance.hotUpdateAssemblyDefinitions) + { + var dll = instanceHotUpdateAssemblyDefinition.name; + File.Copy($"{ScriptAssemblies}{dll}.dll", $"{hotUpdatePath}/{dll}.dll.bytes", true); + File.Copy($"{ScriptAssemblies}{dll}.pdb", $"{hotUpdatePath}/{dll}.pdb.bytes", true); + } + + AssetDatabase.Refresh(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/FantasyStartup.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/FantasyStartup.cs.meta new file mode 100644 index 00000000..abcd77d5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/FantasyStartup.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 42156ba2865a4aa4a3e1e57b3ac9b984 +timeCreated: 1688276977 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/LinkXmlGenerator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/LinkXmlGenerator.cs new file mode 100644 index 00000000..af8cf9bd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/LinkXmlGenerator.cs @@ -0,0 +1,46 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Fantasy +{ + public class LinkXmlGenerator + { + private const string LinkPath = "Assets/link.xml"; + // 在Unity编辑器中运行该方法来生成link.xml文件 + [UnityEditor.MenuItem("Fantasy/Generate link.xml")] + public static void GenerateLinkXml() + { + using (var writer = new StreamWriter("Assets/link.xml")) + { + writer.WriteLine(""); + GenerateLinkXml(writer, "Assembly-CSharp", LinkPath); + Debug.Log("Assembly-CSharp Link generation completed"); + GenerateLinkXml(writer, "Fantasy.Unity", LinkPath); + Debug.Log("Fantasy.Unity Link generation completed"); + foreach (var linkAssembly in FantasySettingsScriptableObject.Instance.linkAssemblyDefinitions) + { + GenerateLinkXml(writer, linkAssembly.name, LinkPath); + Debug.Log($"{linkAssembly.name} Link generation completed"); + } + writer.WriteLine(""); + } + + AssetDatabase.Refresh(); + Debug.Log("link.xml generated successfully!"); + } + + private static void GenerateLinkXml(StreamWriter writer, string assemblyName, string outputPath) + { + var assembly = System.Reflection.Assembly.Load(assemblyName); + var types = assembly.GetTypes(); + writer.WriteLine($" "); + foreach (var type in types) + { + var typeName = type.FullName.Replace('<', '+').Replace('>', '+'); + writer.WriteLine($" "); + } + writer.WriteLine(" "); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/LinkXmlGenerator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/LinkXmlGenerator.cs.meta new file mode 100644 index 00000000..dbab2202 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/LinkXmlGenerator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cda4c9403de946df9c31654416193a21 +timeCreated: 1722743236 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings.meta new file mode 100644 index 00000000..6b097c8b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3a6997d946f3400e8c423fe1b9245f65 +timeCreated: 1688277110 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettings.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettings.cs new file mode 100644 index 00000000..4c85dc7e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettings.cs @@ -0,0 +1,13 @@ +using UnityEditor; + +namespace Fantasy +{ + public class FantasySettings + { + [MenuItem("Fantasy/Fantasy Settings")] + public static void OpenFantasySettings() + { + SettingsService.OpenProjectSettings("Project/Fantasy Settings"); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettings.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettings.cs.meta new file mode 100644 index 00000000..852e825b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 977a7c172c30403da60286ba39b7bc72 +timeCreated: 1686913667 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsProvider.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsProvider.cs new file mode 100644 index 00000000..d1511446 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsProvider.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using UnityEngine.UIElements; + +namespace Fantasy +{ + public class FantasySettingsProvider : SettingsProvider + { + private SerializedObject _serializedObject; + private SerializedProperty _autoCopyAssembly; + private SerializedProperty _hotUpdatePath; + private SerializedProperty _hotUpdateAssemblyDefinitions; + private SerializedProperty _linkAssemblyDefinitions; + public FantasySettingsProvider() : base("Project/Fantasy Settings", SettingsScope.Project) { } + + public override void OnActivate(string searchContext, VisualElement rootElement) + { + Init(); + base.OnActivate(searchContext, rootElement); + } + + public override void OnDeactivate() + { + base.OnDeactivate(); + FantasySettingsScriptableObject.Save(); + } + + private void Init() + { + _serializedObject?.Dispose(); + _serializedObject = new SerializedObject(FantasySettingsScriptableObject.Instance); + _autoCopyAssembly = _serializedObject.FindProperty("autoCopyAssembly"); + _hotUpdatePath = _serializedObject.FindProperty("hotUpdatePath"); + _hotUpdateAssemblyDefinitions = _serializedObject.FindProperty("hotUpdateAssemblyDefinitions"); + _linkAssemblyDefinitions = _serializedObject.FindProperty("linkAssemblyDefinitions"); + } + + public override void OnGUI(string searchContext) + { + if (_serializedObject == null || !_serializedObject.targetObject) + { + Init(); + } + + using (CreateSettingsWindowGUIScope()) + { + _serializedObject!.Update(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(_autoCopyAssembly); + EditorGUILayout.PropertyField(_hotUpdatePath); + EditorGUILayout.PropertyField(_hotUpdateAssemblyDefinitions); + EditorGUILayout.PropertyField(_linkAssemblyDefinitions); + EditorGUILayout.HelpBox("默认包括Assembly-CSharp和Fantasy.Unity,所以不需要再次指定。", MessageType.Info); + + if (GUILayout.Button("GenerateLinkXml")) + { + LinkXmlGenerator.GenerateLinkXml(); + } + + if (EditorGUI.EndChangeCheck()) + { + _serializedObject.ApplyModifiedProperties(); + FantasySettingsScriptableObject.Save(); + EditorApplication.RepaintHierarchyWindow(); + } + + base.OnGUI(searchContext); + } + } + + private IDisposable CreateSettingsWindowGUIScope() + { + var unityEditorAssembly = System.Reflection.Assembly.GetAssembly(typeof(EditorWindow)); + var type = unityEditorAssembly.GetType("UnityEditor.SettingsWindow+GUIScope"); + return Activator.CreateInstance(type) as IDisposable; + } + + static FantasySettingsProvider _provider; + + [SettingsProvider] + public static SettingsProvider CreateMyCustomSettingsProvider() + { + if (FantasySettingsScriptableObject.Instance && _provider == null) + { + _provider = new FantasySettingsProvider(); + using (var so = new SerializedObject(FantasySettingsScriptableObject.Instance)) + { + _provider.keywords = GetSearchKeywordsFromSerializedObject(so); + } + } + return _provider; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsProvider.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsProvider.cs.meta new file mode 100644 index 00000000..72e475d5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsProvider.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 047b2f13e73f413fa000bf7be979fb4a +timeCreated: 1688380387 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsScriptableObject.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsScriptableObject.cs new file mode 100644 index 00000000..919285bb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsScriptableObject.cs @@ -0,0 +1,21 @@ +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Fantasy +{ + [ScriptableObjectPath("ProjectSettings/FantasySettings.asset")] + public class FantasySettingsScriptableObject : ScriptableObjectSingleton, ISerializationCallbackReceiver + { + [FormerlySerializedAs("AutoCopyAssembly")] [Header("自动拷贝程序集到HotUpdatePath目录中")] + public bool autoCopyAssembly = false; + [FormerlySerializedAs("HotUpdatePath")] [Header("HotUpdate目录(Unity编译后会把所有HotUpdate程序集Copy一份到这个目录下)")] + public string hotUpdatePath; + [FormerlySerializedAs("HotUpdateAssemblyDefinitions")] [Header("HotUpdate程序集")] + public AssemblyDefinitionAsset[] hotUpdateAssemblyDefinitions; + [FormerlySerializedAs("LinkAssemblyDefinitions")] [Header("生成Link.xml的程序集")] + public AssemblyDefinitionAsset[] linkAssemblyDefinitions; + public void OnBeforeSerialize() { } + public void OnAfterDeserialize() { } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta new file mode 100644 index 00000000..b5bae5a8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/FantasySettingsScriptableObject.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 27a37e930ca3454fb57bc895f50d2106 +timeCreated: 1688277120 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/ScriptableObjectSingleton.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/ScriptableObjectSingleton.cs new file mode 100644 index 00000000..62066762 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/ScriptableObjectSingleton.cs @@ -0,0 +1,100 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +// ReSharper disable AssignNullToNotNullAttribute + +namespace Fantasy +{ + public class ScriptableObjectSingleton : ScriptableObject where T : ScriptableObject + { + private static T _instance; + + public static T Instance + { + get + { + if (_instance == null) + { + _instance = Load(); + } + + return _instance; + } + } + + private static T Load() + { + var scriptableObjectPath = GetScriptableObjectPath(); + + if (string.IsNullOrEmpty(scriptableObjectPath)) + { + return null; + } + + var loadSerializedFileAndForget = InternalEditorUtility.LoadSerializedFileAndForget(scriptableObjectPath); + + if (loadSerializedFileAndForget.Length <= 0) + { + return CreateInstance(); + } + + return loadSerializedFileAndForget[0] as T; + } + + public static void Save(bool saveAsText = true) + { + if (_instance == null) + { + Debug.LogError("Cannot save ScriptableObjectSingleton: no instance!"); + return; + } + + var scriptableObjectPath = GetScriptableObjectPath(); + + if (string.IsNullOrEmpty(scriptableObjectPath)) + { + return; + } + + var directoryName = Path.GetDirectoryName(scriptableObjectPath); + + if (!Directory.Exists(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + + UnityEngine.Object[] obj = { _instance }; + InternalEditorUtility.SaveToSerializedFileAndForget(obj, scriptableObjectPath, saveAsText); + } + + private static string GetScriptableObjectPath() + { + var scriptableObjectPathAttribute = typeof(T).GetCustomAttribute(typeof(ScriptableObjectPathAttribute)) as ScriptableObjectPathAttribute; + return scriptableObjectPathAttribute?.ScriptableObjectPath; + } + } + + [AttributeUsage(AttributeTargets.Class, Inherited = false)] + public class ScriptableObjectPathAttribute : Attribute + { + internal readonly string ScriptableObjectPath; + + public ScriptableObjectPathAttribute(string scriptableObjectPath) + { + if (string.IsNullOrEmpty(scriptableObjectPath)) + { + throw new ArgumentException("Invalid relative path (it is empty)"); + } + + if (scriptableObjectPath[0] == '/') + { + scriptableObjectPath = scriptableObjectPath.Substring(1); + } + + ScriptableObjectPath = scriptableObjectPath; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/ScriptableObjectSingleton.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/ScriptableObjectSingleton.cs.meta new file mode 100644 index 00000000..5105c6fc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/Settings/ScriptableObjectSingleton.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3c77f5208dc14542ae7497d59321ef76 +timeCreated: 1688278016 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket.meta new file mode 100644 index 00000000..21883b65 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9e5c7d1436ec414fa3f69a23aaafc3b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket/SettingsWindow.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket/SettingsWindow.cs new file mode 100644 index 00000000..0313b0e0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket/SettingsWindow.cs @@ -0,0 +1,229 @@ +using UnityEngine; +using UnityEditor; +using UnityEngine.Networking; +using System.IO; +using System; + +namespace UnityWebSocket.Editor +{ + internal class SettingsWindow : EditorWindow + { + static SettingsWindow window = null; + [MenuItem("Tools/UnityWebSocket", priority = 100)] + internal static void Open() + { + if (window != null) + { + window.Close(); + } + + window = GetWindow(true, "UnityWebSocket"); + window.minSize = window.maxSize = new Vector2(600, 310); + window.Show(); + window.BeginCheck(); + } + + private void OnGUI() + { + DrawLogo(); + DrawVersion(); + DrawSeparator(80); + DrawSeparator(186); + DrawHelper(); + DrawFooter(); + } + + Texture2D logoTex = null; + private void DrawLogo() + { + if (logoTex == null) + { + logoTex = new Texture2D(66, 66); + logoTex.LoadImage(Convert.FromBase64String(LOGO_BASE64.VALUE)); + for (int i = 0; i < 66; i++) for (int j = 0; j < 15; j++) logoTex.SetPixel(i, j, Color.clear); + logoTex.Apply(); + } + + var logoPos = new Rect(10, 10, 66, 66); + GUI.DrawTexture(logoPos, logoTex); + var title = "UnityWebSocket"; + var titlePos = new Rect(80, 20, 500, 50); + GUI.Label(titlePos, title, TextStyle(24)); + } + + private void DrawSeparator(int y) + { + EditorGUI.DrawRect(new Rect(10, y, 580, 1), Color.white * 0.5f); + } + + private GUIStyle TextStyle(int fontSize = 10, TextAnchor alignment = TextAnchor.UpperLeft, float alpha = 0.85f) + { + var style = new GUIStyle(); + style.fontSize = fontSize; + style.normal.textColor = (EditorGUIUtility.isProSkin ? Color.white : Color.black) * alpha; + style.alignment = alignment; + style.richText = true; + return style; + } + + private void DrawVersion() + { + GUI.Label(new Rect(440, 10, 150, 10), "Current Version: " + Settings.VERSION, TextStyle(alignment: TextAnchor.MiddleLeft)); + if (string.IsNullOrEmpty(latestVersion)) + { + GUI.Label(new Rect(440, 30, 150, 10), "Checking for Updates...", TextStyle(alignment: TextAnchor.MiddleLeft)); + } + else if (latestVersion == "unknown") + { + + } + else + { + GUI.Label(new Rect(440, 30, 150, 10), "Latest Version: " + latestVersion, TextStyle(alignment: TextAnchor.MiddleLeft)); + if (Settings.VERSION == latestVersion) + { + if (GUI.Button(new Rect(440, 50, 150, 18), "Check Update")) + { + latestVersion = ""; + changeLog = ""; + BeginCheck(); + } + } + else + { + if (GUI.Button(new Rect(440, 50, 150, 18), "Update to | " + latestVersion)) + { + ShowUpdateDialog(); + } + } + } + } + + private void ShowUpdateDialog() + { + var isOK = EditorUtility.DisplayDialog("UnityWebSocket", + "Update UnityWebSocket now?\n" + changeLog, + "Update Now", "Cancel"); + + if (isOK) + { + UpdateVersion(); + } + } + + private void UpdateVersion() + { + Application.OpenURL(Settings.GITHUB + "/releases"); + } + + private void DrawHelper() + { + GUI.Label(new Rect(330, 200, 100, 18), "GitHub:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 200, 150, 18), "UnityWebSocket")) + { + Application.OpenURL(Settings.GITHUB); + } + + GUI.Label(new Rect(330, 225, 100, 18), "Report:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 225, 150, 18), "Report an Issue")) + { + Application.OpenURL(Settings.GITHUB + "/issues/new"); + } + + GUI.Label(new Rect(330, 250, 100, 18), "Email:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 250, 150, 18), Settings.EMAIL)) + { + var uri = new Uri(string.Format("mailto:{0}?subject={1}", Settings.EMAIL, "UnityWebSocket Feedback")); + Application.OpenURL(uri.AbsoluteUri); + } + + GUI.Label(new Rect(330, 275, 100, 18), "QQ群:", TextStyle(10, TextAnchor.MiddleRight)); + if (GUI.Button(new Rect(440, 275, 150, 18), Settings.QQ_GROUP)) + { + Application.OpenURL(Settings.QQ_GROUP_LINK); + } + } + + private void DrawFooter() + { + EditorGUI.DropShadowLabel(new Rect(10, 230, 400, 20), "Developed by " + Settings.AUHTOR); + EditorGUI.DropShadowLabel(new Rect(10, 250, 400, 20), "All rights reserved"); + } + + UnityWebRequest req; + string changeLog = ""; + string latestVersion = ""; + void BeginCheck() + { + EditorApplication.update -= VersionCheckUpdate; + EditorApplication.update += VersionCheckUpdate; + + req = UnityWebRequest.Get(Settings.GITHUB + "/releases/latest"); + req.SendWebRequest(); + } + + private void VersionCheckUpdate() + { +#if UNITY_2020_3_OR_NEWER + if (req == null + || req.result == UnityWebRequest.Result.ConnectionError + || req.result == UnityWebRequest.Result.DataProcessingError + || req.result == UnityWebRequest.Result.ProtocolError) +#elif UNITY_2018_1_OR_NEWER + if (req == null || req.isNetworkError || req.isHttpError) +#else + if (req == null || req.isError) +#endif + { + EditorApplication.update -= VersionCheckUpdate; + latestVersion = "unknown"; + return; + } + + if (req.isDone) + { + EditorApplication.update -= VersionCheckUpdate; + latestVersion = req.url.Substring(req.url.LastIndexOf("/") + 1).TrimStart('v'); + + if (Settings.VERSION != latestVersion) + { + var text = req.downloadHandler.text; + var st = text.IndexOf("content=\"" + latestVersion); + st = st > 0 ? text.IndexOf("\n", st) : -1; + var end = st > 0 ? text.IndexOf("\" />", st) : -1; + if (st > 0 && end > st) + { + changeLog = text.Substring(st + 1, end - st - 1).Trim(); + changeLog = changeLog.Replace("\r", ""); + changeLog = changeLog.Replace("\n", "\n- "); + changeLog = "\nCHANGE LOG: \n- " + changeLog + "\n"; + } + } + + Repaint(); + } + } + } + + internal static class LOGO_BASE64 + { + internal const string VALUE = "iVBORw0KGgoAAAANSUhEUgAAAEIAAABCCAMAAADUivDaAAAAq1BMVEUAAABKmtcvjtYzl" + + "9szmNszl9syl9k0mNs0mNwzmNs0mNszl9szl9s0mNs0mNwzmNw0mNwyltk0mNw0mNwzl9s0mNsymNs0mNszmNwzmNwzm" + + "NszmNs0mNwzl9w0mNwzmNw0mNs0mNs0mNwzl9wzmNs0mNwzmNs0mNwzl90zmNszmNszl9szmNsxmNszmNszmNw0mNwzm" + + "Nw0mNs2neM4pe41mt43ouo2oOY5qfM+UHlaAAAAMnRSTlMAAwXN3sgI+/069MSCK6M/MA74h9qfFHB8STWMJ9OSdmNcI" + + "8qya1IeF+/U0EIa57mqmFTYJe4AAAN3SURBVFjD7ZbpkppAFEa/bgVBREF2kEVGFNeZsM77P1kadURnJkr8k1Qlx1Khu" + + "/pw7+2lwH/+YcgfMBBLG7VocwDamzH+wJBB8Qhjve2f0TdrGwjei6o4Ub/nM/APw5Z7vvSB/qrCrqbD6fBEVtigeMxks" + + "fX9zWbj+z1jhqgSBplQ50eGo4614WXlRAzgrRhmtSfvxAn7pB0N5ObaKKZZuU5/d37IBcBgUQwqDuf7Z2gUmVAl4NGNr" + + "/UeHxV5n39ulbaKLI86h6HilmM5M1aN126lpNhtl59yeTsp8nUMvpNC1J3bh5FtfVRk+bJrJunn5d4U4piJ/Vw9eXgsj" + + "4ZpZaCjg9waZkIpnBWLJ44OwoNu60F2UnSaEkKv4XnAlCpm6B4F/aKMDiyGi2L8SEEAVdxNLuzmgV7nFwObEe2xQVuX+" + + "RV1lWetga3w+cN1sXgvm4cJH8OEgZC1DPKhfF/BIymmQrMjq/x65FUeEkDup8GxoexZmznHCvANtXU/CAq13yimhQGtm" + + "H4VCPnBBL1fTKo3CqEcvq7Lb/OwHxWTYlyw+JmjKoVvDLVOQB4pVsM8K8smgvLCxZDlIijwyOEc+nr/msMwK0+GQWGBd" + + "tmhjv8icTds1s2ammaFh04QLLe69NK7guP6mTDMaw3o6nAX/Z7EXUskPSvWEWg4srVlp5NTDXv9Lce9HGN5eeG4nj5Yz" + + "ACteU2wQLo4MBtJfd1nw5nG1/s9zwUQ6pykL1TQjqdeuvQW0naz2XKLYL4Cwzr4vj+OQdD96CSp7Lrynp4aeFF0xdm5q" + + "6OFtFfPv7URxpWJNjd/N+3+I9+1klMav12Qtgbt9R2JaIopjkzaPtOFq4KxUpqfUMSFnQrySWjLoQzRZS4HMH84ME1ej" + + "S1YJpQZ3B+sR1uCQJSBdGdCk1eAEgORR88KK05W8dh2MA+A/SKCYu3mCJ0Ek7HBx4HHeuwYy5G3x8hSMTJcOMFbinCsn" + + "hO1V1aszGULvA0g4UFsb4VA0hAFcyo6cgLsAoT7uUtGAH5wQKQle0wuLyxLTaNyJEYwxw4wSljLK1TP8CAaOyhBMMEsj" + + "OBoXgo7VGElFkSWL+vef1RF2YNXeRWYzQBTpkhC8KaZHhuIogArkQLKClBZjU26B2IZgGz+cpZkHl8g3fYUaW/YP2kb2" + + "M/V97JY/vZN859n+QmO7XtC9Bf2jAAAAABJRU5ErkJggg=="; + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket/SettingsWindow.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket/SettingsWindow.cs.meta new file mode 100644 index 00000000..74124688 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Editor/Runtime/WSocket/SettingsWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 902614e06186a482f9e816e1d1984547 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Fantasy.Unity.asmdef b/Fantasy.Unity/Fantasy.Unity.UniTask/Fantasy.Unity.asmdef new file mode 100644 index 00000000..ccfd42a4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Fantasy.Unity.asmdef @@ -0,0 +1,17 @@ +{ + "name": "Fantasy.Unity", + "rootNamespace": "", + "references": [ + "GUID:f51ebe6a0ceec4240a699833d6309b23", + "GUID:77d6c8c98758f884fbc6cb1c9bfb5924" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Fantasy.Unity.asmdef.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Fantasy.Unity.asmdef.meta new file mode 100644 index 00000000..ac113c41 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Fantasy.Unity.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0b7224b83ba514121aa026f3857f820a +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime.meta new file mode 100644 index 00000000..b559b169 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d4180ba95bb674e6488cd44665e784d6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core.meta new file mode 100644 index 00000000..12f960bb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 076d59bda84794582abf2d7b23d3cc01 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly.meta new file mode 100644 index 00000000..19f46f05 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b5b24e6eec64b4702b871053139f8add +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblyInfo.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblyInfo.cs new file mode 100644 index 00000000..60db3fda --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblyInfo.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Fantasy.DataStructure.Collection; + +// ReSharper disable CollectionNeverQueried.Global +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Assembly +{ + /// + /// AssemblyInfo提供有关程序集和类型的信息 + /// + public sealed class AssemblyInfo + { + /// + /// 唯一标识 + /// + public readonly long AssemblyIdentity; + /// + /// 获取或设置与此程序集相关联的 实例。 + /// + public System.Reflection.Assembly Assembly { get; private set; } + /// + /// 程序集类型集合,获取一个列表,包含从程序集加载的所有类型。 + /// + public readonly List AssemblyTypeList = new List(); + /// + /// 程序集类型分组集合,获取一个分组列表,将接口类型映射到实现这些接口的类型。 + /// + public readonly OneToManyList AssemblyTypeGroupList = new OneToManyList(); + + /// + /// 初始化 类的新实例。 + /// + /// + public AssemblyInfo(long assemblyIdentity) + { + AssemblyIdentity = assemblyIdentity; + } + + /// + /// 从指定的程序集加载类型信息并进行分类。 + /// + /// 要加载信息的程序集。 + public void Load(System.Reflection.Assembly assembly) + { + Assembly = assembly; + var assemblyTypes = assembly.GetTypes().ToList(); + + foreach (var type in assemblyTypes) + { + if (type.IsAbstract || type.IsInterface) + { + continue; + } + + var interfaces = type.GetInterfaces(); + + foreach (var interfaceType in interfaces) + { + AssemblyTypeGroupList.Add(interfaceType, type); + } + } + + AssemblyTypeList.AddRange(assemblyTypes); + } + + /// + /// 卸载程序集的类型信息。 + /// + public void Unload() + { + AssemblyTypeList.Clear(); + AssemblyTypeGroupList.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblyInfo.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblyInfo.cs.meta new file mode 100644 index 00000000..b5e3a284 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6588e9470957646dfa79849126de341c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblySystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblySystem.cs new file mode 100644 index 00000000..c72b8675 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblySystem.cs @@ -0,0 +1,262 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Helper; + +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8603 +#pragma warning disable CS8618 +namespace Fantasy.Assembly +{ + /// + /// 管理程序集加载和卸载的帮助类。 + /// + public static class AssemblySystem + { +#if FANTASY_WEBGL + private static readonly List AssemblySystems = new List(); + private static readonly Dictionary AssemblyList = new Dictionary(); +#else + private static readonly ConcurrentBag AssemblySystems = new ConcurrentBag(); + private static readonly ConcurrentDictionary AssemblyList = new ConcurrentDictionary(); +#endif + /// + /// 初始化 AssemblySystem。 + /// + public static void Initialize(params System.Reflection.Assembly[] assemblies) + { + LoadAssembly(typeof(AssemblySystem).Assembly); + foreach (var assembly in assemblies) + { + LoadAssembly(assembly); + } + } + + /// + /// 加载指定的程序集,并触发相应的事件。 + /// + /// 要加载的程序集。 + public static void LoadAssembly(System.Reflection.Assembly assembly) + { + var assemblyIdentity = AssemblyIdentity(assembly); + + if (AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo)) + { + assemblyInfo.Unload(); + foreach (var assemblySystem in AssemblySystems) + { + assemblySystem.ReLoad(assemblyIdentity); + } + } + else + { + assemblyInfo = new AssemblyInfo(assemblyIdentity); + AssemblyList.TryAdd(assemblyIdentity, assemblyInfo); + foreach (var assemblySystem in AssemblySystems) + { + assemblySystem.Load(assemblyIdentity); + } + } + + assemblyInfo.Load(assembly); + } + + /// + /// 卸载程序集 + /// + /// + public static void UnLoadAssembly(System.Reflection.Assembly assembly) + { + var assemblyIdentity = AssemblyIdentity(assembly); + + if (!AssemblyList.Remove(assemblyIdentity, out var assemblyInfo)) + { + return; + } + + assemblyInfo.Unload(); + foreach (var assemblySystem in AssemblySystems) + { + assemblySystem.OnUnLoad(assemblyIdentity); + } + } + + /// + /// 将AssemblySystem接口的object注册到程序集管理中心 + /// + /// + public static async UniTask Register(object obj) + { + if (obj is not IAssembly assemblySystem) + { + return; + } + + AssemblySystems.Add(assemblySystem); + + foreach (var (assemblyIdentity, _) in AssemblyList) + { + await assemblySystem.Load(assemblyIdentity); + } + } + + /// + /// 程序集管理中心卸载注册的Load、ReLoad、UnLoad的接口 + /// + /// + public static void UnRegister(object obj) + { + if (obj is not IAssembly assemblySystem) + { + return; + } +#if FANTASY_WEBGL + AssemblySystems.Remove(assemblySystem); +#else + while (AssemblySystems.TryTake(out var removeAssemblySystem)) + { + if (removeAssemblySystem == assemblySystem) + { + continue; + } + + AssemblySystems.Add(removeAssemblySystem); + } +#endif + } + + /// + /// 获取所有已加载程序集中的所有类型。 + /// + /// 所有已加载程序集中的类型。 + public static IEnumerable ForEach() + { + foreach (var (_, assemblyInfo) in AssemblyList) + { + foreach (var type in assemblyInfo.AssemblyTypeList) + { + yield return type; + } + } + } + + /// + /// 获取指定程序集中的所有类型。 + /// + /// 程序集唯一标识。 + /// 指定程序集中的类型。 + public static IEnumerable ForEach(long assemblyIdentity) + { + if (!AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo)) + { + yield break; + } + + foreach (var type in assemblyInfo.AssemblyTypeList) + { + yield return type; + } + } + + /// + /// 获取所有已加载程序集中实现指定类型的所有类型。 + /// + /// 要查找的基类或接口类型。 + /// 所有已加载程序集中实现指定类型的类型。 + public static IEnumerable ForEach(Type findType) + { + foreach (var (_, assemblyInfo) in AssemblyList) + { + if (!assemblyInfo.AssemblyTypeGroupList.TryGetValue(findType, out var assemblyLoad)) + { + continue; + } + + foreach (var type in assemblyLoad) + { + yield return type; + } + } + } + + /// + /// 获取指定程序集中实现指定类型的所有类型。 + /// + /// 程序集唯一标识。 + /// 要查找的基类或接口类型。 + /// 指定程序集中实现指定类型的类型。 + public static IEnumerable ForEach(long assemblyIdentity, Type findType) + { + if (!AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo)) + { + yield break; + } + + if (!assemblyInfo.AssemblyTypeGroupList.TryGetValue(findType, out var assemblyLoad)) + { + yield break; + } + + foreach (var type in assemblyLoad) + { + yield return type; + } + } + + /// + /// 获取指定程序集的实例。 + /// + /// 程序集名称。 + /// 指定程序集的实例,如果未加载则返回 null。 + public static System.Reflection.Assembly GetAssembly(long assemblyIdentity) + { + return !AssemblyList.TryGetValue(assemblyIdentity, out var assemblyInfo) ? null : assemblyInfo.Assembly; + } + + /// + /// 获取当前框架注册的Assembly + /// + /// + public static IEnumerable ForEachAssembly + { + get + { + foreach (var (_, assemblyInfo) in AssemblyList) + { + yield return assemblyInfo.Assembly; + } + } + } + + /// + /// 根据Assembly的强命名计算唯一标识。 + /// + /// + /// + private static long AssemblyIdentity(System.Reflection.Assembly assembly) + { + return HashCodeHelper.ComputeHash64(assembly.GetName().Name); + } + + /// + /// 释放资源,卸载所有加载的程序集。 + /// + public static void Dispose() + { + foreach (var (_, assemblyInfo) in AssemblyList.ToArray()) + { + UnLoadAssembly(assemblyInfo.Assembly); + } + + AssemblyList.Clear(); + AssemblySystems.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblySystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblySystem.cs.meta new file mode 100644 index 00000000..6474bd99 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/AssemblySystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6f06892fa649d49c287bf07095569ae0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/IAssembly.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/IAssembly.cs new file mode 100644 index 00000000..487d4df5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/IAssembly.cs @@ -0,0 +1,28 @@ +using System; +using Cysharp.Threading.Tasks; +using Fantasy.Async; + +namespace Fantasy.Assembly +{ + /// + /// 实现这个接口、会再程序集首次加载、卸载、重载的时候调用 + /// + public interface IAssembly : IDisposable + { + /// + /// 程序集加载时调用 + /// + /// 程序集标识 + public UniTask Load(long assemblyIdentity); + /// + /// 程序集重新加载的时候调用 + /// + /// 程序集标识 + public UniTask ReLoad(long assemblyIdentity); + /// + /// 卸载的时候调用 + /// + /// 程序集标识 + public UniTask OnUnLoad(long assemblyIdentity); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/IAssembly.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/IAssembly.cs.meta new file mode 100644 index 00000000..11db0dc6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Assembly/IAssembly.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f14fcbf29decc4d47b6c548a3d5f2a3f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark.meta new file mode 100644 index 00000000..cfe3201a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 160974fcbccd74d0eafedf8762807588 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler.meta new file mode 100644 index 00000000..cfda7e8e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 91eb4278fcdd44b6d8a782ca42107e4c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs new file mode 100644 index 00000000..85325479 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs @@ -0,0 +1,25 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Benchmark.Handler; + +/// +/// BenchmarkRequestHandler +/// +public sealed class BenchmarkRequestHandler : MessageRPC +{ + /// + /// Run方法 + /// + /// + /// + /// + /// + protected override async FTask Run(Session session, BenchmarkRequest request, BenchmarkResponse response, Action reply) + { + await FTask.CompletedTask; + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta new file mode 100644 index 00000000..e0451e32 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Benchmark/Handler/BenchmarkRequestHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b5a936197cf64719b8d6b44158e0d91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase.meta new file mode 100644 index 00000000..5a4bdb5b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4961a2a852e804ad69bad45492f22555 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/IDataBase.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/IDataBase.cs new file mode 100644 index 00000000..9b08c8eb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/IDataBase.cs @@ -0,0 +1,164 @@ +#if FANTASY_NET +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using Fantasy.Async; +using Fantasy.Entitas; + +#pragma warning disable CS8625 + +namespace Fantasy.DataBase +{ + /// + /// 表示用于执行各种数据库操作的数据库接口。 + /// + public interface IDataBase + { + /// + /// 初始化数据库连接。 + /// + IDataBase Initialize(Scene scene, string connectionString, string dbName); + /// + /// 在指定的集合中检索类型 的实体数量。 + /// + FTask Count(string collection = null) where T : Entity; + /// + /// 在指定的集合中检索满足给定筛选条件的类型 的实体数量。 + /// + FTask Count(Expression> filter, string collection = null) where T : Entity; + /// + /// 检查指定集合中是否存在类型 的实体。 + /// + FTask Exist(string collection = null) where T : Entity; + /// + /// 检查指定集合中是否存在满足给定筛选条件的类型 的实体。 + /// + FTask Exist(Expression> filter, string collection = null) where T : Entity; + /// + /// 从指定集合中检索指定 ID 的类型 的实体,不锁定。 + /// + FTask QueryNotLock(long id, string collection = null) where T : Entity; + /// + /// 从指定集合中检索指定 ID 的类型 的实体。 + /// + FTask Query(long id, string collection = null) where T : Entity; + /// + /// 按页查询满足给定筛选条件的类型 的实体数量和日期。 + /// + FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, string collection = null) where T : Entity; + /// + /// 按页查询满足给定筛选条件的类型 的实体数量和日期。 + /// + FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, string collection = null) where T : Entity; + /// + /// 分页查询指定集合中满足给定筛选条件的类型 的实体列表。 + /// + FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, string collection = null) where T : Entity; + /// + /// 分页查询指定集合中满足给定筛选条件的类型 的实体列表,仅返回指定列的数据。 + /// + FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, string collection = null) where T : Entity; + /// + /// 从指定集合中按页查询满足给定筛选条件的类型 的实体列表,按指定字段排序。 + /// + FTask> QueryByPageOrderBy(Expression> filter, int pageIndex, int pageSize, Expression> orderByExpression, bool isAsc = true, string collection = null) where T : Entity; + /// + /// 检索满足给定筛选条件的类型 的第一个实体,从指定集合中。 + /// + FTask First(Expression> filter, string collection = null) where T : Entity; + /// + /// 查询指定集合中满足给定 JSON 查询字符串的类型 的第一个实体,仅返回指定列的数据。 + /// + FTask First(string json, string[] cols, string collection = null) where T : Entity; + /// + /// 从指定集合中按页查询满足给定筛选条件的类型 的实体列表,按指定字段排序。 + /// + FTask> QueryOrderBy(Expression> filter, Expression> orderByExpression, bool isAsc = true, string collection = null) where T : Entity; + /// + /// 从指定集合中按页查询满足给定筛选条件的类型 的实体列表。 + /// + FTask> Query(Expression> filter, string collection = null) where T : Entity; + /// + /// 查询指定 ID 的多个集合,将结果存储在给定的实体列表中。 + /// + FTask Query(long id, List collectionNames, List result); + /// + /// 根据给定的 JSON 查询字符串查询指定集合中的类型 实体列表。 + /// + FTask> QueryJson(string json, string collection = null) where T : Entity; + /// + /// 根据给定的 JSON 查询字符串查询指定集合中的类型 实体列表,仅返回指定列的数据。 + /// + FTask> QueryJson(string json, string[] cols, string collection = null) where T : Entity; + /// + /// 根据给定的 JSON 查询字符串查询指定集合中的类型 实体列表,通过指定的任务 ID 进行标识。 + /// + FTask> QueryJson(long taskId, string json, string collection = null) where T : Entity; + /// + /// 查询指定集合中满足给定筛选条件的类型 实体列表,仅返回指定列的数据。 + /// + FTask> Query(Expression> filter, string[] cols, string collection = null) where T : class; + /// + /// 保存类型 实体到指定集合中,如果集合不存在将自动创建。 + /// + FTask Save(T entity, string collection = null) where T : Entity, new(); + /// + /// 保存一组实体到数据库中,根据实体列表的 ID 进行区分和存储。 + /// + FTask Save(long id, List entities); + /// + /// 通过事务会话将类型 实体保存到指定集合中,如果集合不存在将自动创建。 + /// + FTask Save(object transactionSession, T entity, string collection = null) where T : Entity; + /// + /// 向指定集合中插入一个类型 实体,如果集合不存在将自动创建。 + /// + FTask Insert(T entity, string collection = null) where T : Entity, new(); + /// + /// 批量插入一组类型 实体到指定集合中,如果集合不存在将自动创建。 + /// + FTask InsertBatch(IEnumerable list, string collection = null) where T : Entity, new(); + /// + /// 通过事务会话,批量插入一组类型 实体到指定集合中,如果集合不存在将自动创建。 + /// + FTask InsertBatch(object transactionSession, IEnumerable list, string collection = null) where T : Entity, new(); + /// + /// 通过事务会话,根据指定的 ID 从数据库中删除指定类型 实体。 + /// + FTask Remove(object transactionSession, long id, string collection = null) where T : Entity, new(); + /// + /// 根据指定的 ID 从数据库中删除指定类型 实体。 + /// + FTask Remove(long id, string collection = null) where T : Entity, new(); + /// + /// 通过事务会话,根据给定的筛选条件从数据库中删除指定类型 实体。 + /// + FTask Remove(long coroutineLockQueueKey, object transactionSession, Expression> filter, string collection = null) where T : Entity, new(); + /// + /// 根据给定的筛选条件从数据库中删除指定类型 实体。 + /// + FTask Remove(long coroutineLockQueueKey, Expression> filter, string collection = null) where T : Entity, new(); + /// + /// 根据给定的筛选条件计算指定集合中类型 实体某个属性的总和。 + /// + FTask Sum(Expression> filter, Expression> sumExpression, string collection = null) where T : Entity; + /// + /// 在指定的集合中创建索引,以提高类型 实体的查询性能。 + /// + FTask CreateIndex(string collection, params object[] keys) where T : Entity; + /// + /// 在默认集合中创建索引,以提高类型 实体的查询性能。 + /// + FTask CreateIndex(params object[] keys) where T : Entity; + /// + /// 创建指定类型 的数据库,用于存储实体。 + /// + FTask CreateDB() where T : Entity; + /// + /// 根据指定类型创建数据库,用于存储实体。 + /// + FTask CreateDB(Type type); + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/IDataBase.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/IDataBase.cs.meta new file mode 100644 index 00000000..9be13ba1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/IDataBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83202aeeb0df040de8735030956ca861 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/MongoDataBase.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/MongoDataBase.cs new file mode 100644 index 00000000..47582732 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/MongoDataBase.cs @@ -0,0 +1,822 @@ +#if FANTASY_NET +using System.Linq.Expressions; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Helper; +using Fantasy.Serialize; +using MongoDB.Bson; +using MongoDB.Driver; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.DataBase +{ + /// + /// 使用 MongoDB 数据库的实现。 + /// + public sealed class MongoDataBase : IDataBase + { + private const int DefaultTaskSize = 1024; + private Scene _scene; + private string _dbName; + private string _connectionString; + private MongoClient _mongoClient; + private ISerialize _serializer; + private IMongoDatabase _mongoDatabase; + private CoroutineLock _dataBaseLock; + private readonly HashSet _collections = new HashSet(); + + /// + /// 初始化 MongoDB 数据库连接并记录所有集合名。 + /// + /// 所在的Scene。 + /// 数据库连接字符串。 + /// 数据库名称。 + /// 初始化后的数据库实例。 + public IDataBase Initialize(Scene scene, string connectionString, string dbName) + { + _scene = scene; + _dbName = dbName; + _connectionString = connectionString; + _mongoClient = new MongoClient(connectionString); + _mongoDatabase = _mongoClient.GetDatabase(dbName); + _dataBaseLock = scene.CoroutineLockComponent.Create(GetType().TypeHandle.Value.ToInt64()); + // 记录所有集合名 + _collections.UnionWith(_mongoDatabase.ListCollectionNames().ToList()); + _serializer = SerializerManager.GetSerializer(FantasySerializerType.Bson); + return this; + } + + #region Other + + /// + /// 对满足条件的文档中的某个数值字段进行求和操作。 + /// + /// 实体类型。 + /// 用于筛选文档的表达式。 + /// 要对其进行求和的字段表达式。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 满足条件的文档中指定字段的求和结果。 + public async FTask Sum(Expression> filter, Expression> sumExpression, string collection = null) where T : Entity + { + var member = (MemberExpression)((UnaryExpression)sumExpression.Body).Operand; + var projection = new BsonDocument("_id", "null").Add("Result", new BsonDocument("$sum", $"${member.Member.Name}")); + var data = await GetCollection(collection).Aggregate().Match(filter).Group(projection).FirstOrDefaultAsync(); + return data == null ? 0 : Convert.ToInt64(data["Result"]); + } + + #endregion + + #region GetCollection + + /// + /// 获取指定集合中的 MongoDB 文档的 IMongoCollection 对象。 + /// + /// 实体类型。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// IMongoCollection 对象。 + private IMongoCollection GetCollection(string collection = null) + { + return _mongoDatabase.GetCollection(collection ?? typeof(T).Name); + } + + /// + /// 获取指定集合中的 MongoDB 文档的 IMongoCollection 对象,其中实体类型为 Entity。 + /// + /// 集合名称。 + /// IMongoCollection 对象。 + private IMongoCollection GetCollection(string name) + { + return _mongoDatabase.GetCollection(name); + } + + #endregion + + #region Count + + /// + /// 统计指定集合中满足条件的文档数量。 + /// + /// 实体类型。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 满足条件的文档数量。 + public async FTask Count(string collection = null) where T : Entity + { + return await GetCollection(collection).CountDocumentsAsync(d => true); + } + + /// + /// 统计指定集合中满足条件的文档数量。 + /// + /// 实体类型。 + /// 用于筛选文档的表达式。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 满足条件的文档数量。 + public async FTask Count(Expression> filter, string collection = null) where T : Entity + { + return await GetCollection(collection).CountDocumentsAsync(filter); + } + + #endregion + + #region Exist + + /// + /// 判断指定集合中是否存在文档。 + /// + /// 实体类型。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 如果存在文档则返回 true,否则返回 false。 + public async FTask Exist(string collection = null) where T : Entity + { + return await Count(collection) > 0; + } + + /// + /// 判断指定集合中是否存在满足条件的文档。 + /// + /// 实体类型。 + /// 用于筛选文档的表达式。 + /// 集合名称,可选。如果未指定,将使用实体类型的名称。 + /// 如果存在满足条件的文档则返回 true,否则返回 false。 + public async FTask Exist(Expression> filter, string collection = null) where T : Entity + { + return await Count(filter, collection) > 0; + } + + #endregion + + #region Query + + /// + /// 在不加数据库锁定的情况下,查询指定 ID 的文档。 + /// + /// 文档实体类型。 + /// 要查询的文档 ID。 + /// 集合名称。 + /// 查询到的文档。 + public async FTask QueryNotLock(long id, string collection = null) where T : Entity + { + var cursor = await GetCollection(collection).FindAsync(d => d.Id == id); + var v = await cursor.FirstOrDefaultAsync(); + return v; + } + + /// + /// 查询指定 ID 的文档,并加数据库锁定以确保数据一致性。 + /// + /// 文档实体类型。 + /// 要查询的文档 ID。 + /// 集合名称。 + /// 查询到的文档。 + public async FTask Query(long id, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(id)) + { + var cursor = await GetCollection(collection).FindAsync(d => d.Id == id); + var v = await cursor.FirstOrDefaultAsync(); + return v; + } + } + + /// + /// 通过分页查询并返回满足条件的文档数量和日期列表(不加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 集合名称。 + /// 满足条件的文档数量和日期列表。 + public async FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var count = await Count(filter); + var dates = await QueryByPage(filter, pageIndex, pageSize, collection); + return ((int)count, dates); + } + } + + /// + /// 通过分页查询并返回满足条件的文档数量和日期列表(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 要查询的列名称数组。 + /// 集合名称。 + /// 满足条件的文档数量和日期列表。 + public async FTask<(int count, List dates)> QueryCountAndDatesByPage(Expression> filter, int pageIndex, int pageSize, string[] cols, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var count = await Count(filter); + + var dates = await QueryByPage(filter, pageIndex, pageSize, cols, collection); + + return ((int)count, dates); + } + } + + /// + /// 通过分页查询并返回满足条件的文档列表(不加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + return await GetCollection(collection).Find(filter).Skip((pageIndex - 1) * pageSize) + .Limit(pageSize) + .ToListAsync(); + } + } + + /// + /// 通过分页查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 要查询的列名称数组。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryByPage(Expression> filter, int pageIndex, int pageSize, + string[] cols, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(""); + + foreach (var col in cols) + { + projection = projection.Include(col); + } + + return await GetCollection(collection).Find(filter).Project(projection) + .Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); + } + } + + /// + /// 通过分页查询并返回满足条件的文档列表,并按指定表达式进行排序(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 页码。 + /// 每页大小。 + /// 排序表达式。 + /// 是否升序排序。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryByPageOrderBy(Expression> filter, int pageIndex, int pageSize, + Expression> orderByExpression, bool isAsc = true, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + if (isAsc) + { + return await GetCollection(collection).Find(filter).SortBy(orderByExpression) + .Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); + } + + return await GetCollection(collection).Find(filter).SortByDescending(orderByExpression) + .Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); + } + } + + /// + /// 通过指定过滤条件查询并返回满足条件的第一个文档(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 集合名称。 + /// 满足条件的第一个文档,如果未找到则为 null。 + public async FTask First(Expression> filter, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var cursor = await GetCollection(collection).FindAsync(filter); + + return await cursor.FirstOrDefaultAsync(); + } + } + + /// + /// 通过指定 JSON 格式查询并返回满足条件的第一个文档(加锁)。 + /// + /// 文档实体类型。 + /// JSON 查询条件。 + /// 要查询的列名称数组。 + /// 集合名称。 + /// 满足条件的第一个文档。 + public async FTask First(string json, string[] cols, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(""); + + foreach (var col in cols) + { + projection = projection.Include(col); + } + + var options = new FindOptions { Projection = projection }; + + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + + var cursor = await GetCollection(collection).FindAsync(filterDefinition, options); + + return await cursor.FirstOrDefaultAsync(); + } + } + + /// + /// 通过指定过滤条件查询并返回满足条件的文档列表,并按指定表达式进行排序(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 排序表达式。 + /// 是否升序排序。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryOrderBy(Expression> filter, + Expression> orderByExpression, bool isAsc = true, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + if (isAsc) + { + return await GetCollection(collection).Find(filter).SortBy(orderByExpression).ToListAsync(); + } + + return await GetCollection(collection).Find(filter).SortByDescending(orderByExpression) + .ToListAsync(); + } + } + + /// + /// 通过指定过滤条件查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> Query(Expression> filter, string collection = null) + where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var cursor = await GetCollection(collection).FindAsync(filter); + var v = await cursor.ToListAsync(); + return v; + } + } + + /// + /// 根据指定 ID 加锁查询多个集合中的文档。 + /// + /// 文档 ID。 + /// 要查询的集合名称列表。 + /// 查询结果存储列表。 + public async FTask Query(long id, List? collectionNames, List result) + { + using (await _dataBaseLock.Wait(id)) + { + if (collectionNames == null || collectionNames.Count == 0) + { + return; + } + + foreach (var collectionName in collectionNames) + { + var cursor = await GetCollection(collectionName).FindAsync(d => d.Id == id); + + var e = await cursor.FirstOrDefaultAsync(); + + if (e == null) + { + continue; + } + + result.Add(e); + } + } + } + + /// + /// 根据指定的 JSON 查询条件查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// JSON 查询条件。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryJson(string json, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + var cursor = await GetCollection(collection).FindAsync(filterDefinition); + var v = await cursor.ToListAsync(); + return v; + } + } + + /// + /// 根据指定的 JSON 查询条件查询并返回满足条件的文档列表,并选择指定的列(加锁)。 + /// + /// 文档实体类型。 + /// JSON 查询条件。 + /// 要查询的列名称数组。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryJson(string json, string[] cols, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(""); + + foreach (var col in cols) + { + projection = projection.Include(col); + } + + var options = new FindOptions { Projection = projection }; + + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + + var cursor = await GetCollection(collection).FindAsync(filterDefinition, options); + var v = await cursor.ToListAsync(); + return v; + } + } + + /// + /// 根据指定的 JSON 查询条件和任务 ID 查询并返回满足条件的文档列表(加锁)。 + /// + /// 文档实体类型。 + /// 任务 ID。 + /// JSON 查询条件。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> QueryJson(long taskId, string json, string collection = null) where T : Entity + { + using (await _dataBaseLock.Wait(taskId)) + { + FilterDefinition filterDefinition = new JsonFilterDefinition(json); + var cursor = await GetCollection(collection).FindAsync(filterDefinition); + var v = await cursor.ToListAsync(); + return v; + } + } + + /// + /// 根据指定过滤条件查询并返回满足条件的文档列表,选择指定的列(加锁)。 + /// + /// 文档实体类型。 + /// 查询过滤条件。 + /// 要查询的列名称数组。 + /// 集合名称。 + /// 满足条件的文档列表。 + public async FTask> Query(Expression> filter, string[] cols, string collection = null) + where T : class + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + var projection = Builders.Projection.Include(cols[0]); + + for (var i = 1; i < cols.Length; i++) + { + projection = projection.Include(cols[i]); + } + + return await GetCollection(collection).Find(filter).Project(projection).ToListAsync(); + } + } + + #endregion + + #region Save + + /// + /// 保存实体对象到数据库(加锁)。 + /// + /// 实体类型。 + /// 事务会话对象。 + /// 要保存的实体对象。 + /// 集合名称。 + public async FTask Save(object transactionSession, T? entity, string collection = null) where T : Entity + { + if (entity == null) + { + Log.Error($"save entity is null: {typeof(T).Name}"); + return; + } + + var clone = _serializer.Clone(entity); + + using (await _dataBaseLock.Wait(clone.Id)) + { + await GetCollection(collection ?? clone.GetType().Name).ReplaceOneAsync( + (IClientSessionHandle)transactionSession, d => d.Id == clone.Id, clone, + new ReplaceOptions { IsUpsert = true }); + } + } + + /// + /// 保存实体对象到数据库(加锁)。 + /// + /// 实体类型。 + /// 要保存的实体对象。 + /// 集合名称。 + public async FTask Save(T? entity, string collection = null) where T : Entity, new() + { + if (entity == null) + { + Log.Error($"save entity is null: {typeof(T).Name}"); + + return; + } + + var clone = _serializer.Clone(entity); + + using (await _dataBaseLock.Wait(clone.Id)) + { + await GetCollection(collection ?? clone.GetType().Name).ReplaceOneAsync(d => d.Id == clone.Id, clone, + new ReplaceOptions { IsUpsert = true }); + } + } + + /// + /// 保存多个实体对象到数据库(加锁)。 + /// + /// 文档 ID。 + /// 要保存的实体对象列表。 + public async FTask Save(long id, List? entities) + { + if (entities == null || entities.Count == 0) + { + Log.Error("save entity is null"); + return; + } + + using var listPool = ListPool.Create(); + + foreach (var entity in entities) + { + listPool.Add(_serializer.Clone(entity)); + } + + using (await _dataBaseLock.Wait(id)) + { + foreach (var clone in listPool) + { + try + { + await GetCollection(clone.GetType().Name).ReplaceOneAsync(d => d.Id == clone.Id, clone, + new ReplaceOptions { IsUpsert = true }); + } + catch (Exception e) + { + Log.Error($"Save List Entity Error: {clone.GetType().Name} {clone}\n{e}"); + } + } + } + } + + #endregion + + #region Insert + + /// + /// 插入单个实体对象到数据库(加锁)。 + /// + /// 实体类型。 + /// 要插入的实体对象。 + /// 集合名称。 + public FTask Insert(T entity, string collection = null) where T : Entity, new() + { + return Save(entity); + } + + /// + /// 批量插入实体对象列表到数据库(加锁)。 + /// + /// 实体类型。 + /// 要插入的实体对象列表。 + /// 集合名称。 + public async FTask InsertBatch(IEnumerable list, string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + await GetCollection(collection ?? typeof(T).Name).InsertManyAsync(list); + } + } + + /// + /// 批量插入实体对象列表到数据库(加锁)。 + /// + /// 实体类型。 + /// 事务会话对象。 + /// 要插入的实体对象列表。 + /// 集合名称。 + public async FTask InsertBatch(object transactionSession, IEnumerable list, string collection = null) + where T : Entity, new() + { + using (await _dataBaseLock.Wait(RandomHelper.RandInt64() % DefaultTaskSize)) + { + await GetCollection(collection ?? typeof(T).Name) + .InsertManyAsync((IClientSessionHandle)transactionSession, list); + } + } + + #endregion + + #region Remove + + /// + /// 根据ID删除单个实体对象(加锁)。 + /// + /// 实体类型。 + /// 事务会话对象。 + /// 要删除的实体的ID。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(object transactionSession, long id, string collection = null) + where T : Entity, new() + { + using (await _dataBaseLock.Wait(id)) + { + var result = await GetCollection(collection) + .DeleteOneAsync((IClientSessionHandle)transactionSession, d => d.Id == id); + return result.DeletedCount; + } + } + + /// + /// 根据ID删除单个实体对象(加锁)。 + /// + /// 实体类型。 + /// 要删除的实体的ID。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(long id, string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(id)) + { + var result = await GetCollection(collection).DeleteOneAsync(d => d.Id == id); + return result.DeletedCount; + } + } + + /// + /// 根据ID和筛选条件删除多个实体对象(加锁)。 + /// + /// 实体类型。 + /// 异步锁Id。 + /// 事务会话对象。 + /// 筛选条件。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(long coroutineLockQueueKey, object transactionSession, + Expression> filter, string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(coroutineLockQueueKey)) + { + var result = await GetCollection(collection) + .DeleteManyAsync((IClientSessionHandle)transactionSession, filter); + return result.DeletedCount; + } + } + + /// + /// 根据ID和筛选条件删除多个实体对象(加锁)。 + /// + /// 实体类型。 + /// 异步锁Id。 + /// 筛选条件。 + /// 集合名称。 + /// 删除的实体数量。 + public async FTask Remove(long coroutineLockQueueKey, Expression> filter, + string collection = null) where T : Entity, new() + { + using (await _dataBaseLock.Wait(coroutineLockQueueKey)) + { + var result = await GetCollection(collection).DeleteManyAsync(filter); + return result.DeletedCount; + } + } + + #endregion + + #region Index + + /// + /// 创建数据库索引(加锁)。 + /// + /// + /// + /// + /// + /// 使用例子(可多个): + /// 1 : Builders.IndexKeys.Ascending(d=>d.Id) + /// 2 : Builders.IndexKeys.Descending(d=>d.Id).Ascending(d=>d.Name) + /// 3 : Builders.IndexKeys.Descending(d=>d.Id),Builders.IndexKeys.Descending(d=>d.Name) + /// + public async FTask CreateIndex(string collection, params object[]? keys) where T : Entity + { + if (keys == null || keys.Length <= 0) + { + return; + } + + var indexModels = new List>(); + + foreach (object key in keys) + { + IndexKeysDefinition indexKeysDefinition = (IndexKeysDefinition)key; + + indexModels.Add(new CreateIndexModel(indexKeysDefinition)); + } + + await GetCollection(collection).Indexes.CreateManyAsync(indexModels); + } + + /// + /// 创建数据库的索引(加锁)。 + /// + /// 实体类型。 + /// 索引键定义。 + public async FTask CreateIndex(params object[]? keys) where T : Entity + { + if (keys == null) + { + return; + } + + List> indexModels = new List>(); + + foreach (object key in keys) + { + IndexKeysDefinition indexKeysDefinition = (IndexKeysDefinition)key; + + indexModels.Add(new CreateIndexModel(indexKeysDefinition)); + } + + await GetCollection().Indexes.CreateManyAsync(indexModels); + } + + #endregion + + #region CreateDB + + /// + /// 创建数据库集合(如果不存在)。 + /// + /// 实体类型。 + public async FTask CreateDB() where T : Entity + { + // 已经存在数据库表 + string name = typeof(T).Name; + + if (_collections.Contains(name)) + { + return; + } + + await _mongoDatabase.CreateCollectionAsync(name); + + _collections.Add(name); + } + + /// + /// 创建数据库集合(如果不存在)。 + /// + /// 实体类型。 + public async FTask CreateDB(Type type) + { + string name = type.Name; + + if (_collections.Contains(name)) + { + return; + } + + await _mongoDatabase.CreateCollectionAsync(name); + + _collections.Add(name); + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/MongoDataBase.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/MongoDataBase.cs.meta new file mode 100644 index 00000000..b26748a9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/MongoDataBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 366dcc82090f0466da2c2b8d0e6fa2c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/World.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/World.cs new file mode 100644 index 00000000..d0a1b1a9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/World.cs @@ -0,0 +1,83 @@ +#pragma warning disable CS8603 // Possible null reference return. +#if FANTASY_NET +using Fantasy.Platform.Net; + +namespace Fantasy.DataBase +{ + /// + /// 表示一个游戏世界。 + /// + public sealed class World + { + /// + /// 获取游戏世界的唯一标识。 + /// + public byte Id { get; private init; } + /// + /// 获取游戏世界的数据库接口。 + /// + public IDataBase DataBase { get; private init; } + /// + /// 获取游戏世界的配置信息。 + /// + public WorldConfig Config => WorldConfigData.Instance.Get(Id); + /// + /// 用于存储已创建的游戏世界实例 + /// + private static readonly Dictionary Worlds = new(); + + /// + /// 使用指定的配置信息创建一个游戏世界实例。 + /// + /// + /// + public World(Scene scene, byte worldConfigId) + { + Id = worldConfigId; + var worldConfig = Config; + var dbType = worldConfig.DbType.ToLower(); + + switch (dbType) + { + case "mongodb": + { + DataBase = new MongoDataBase(); + DataBase.Initialize(scene, worldConfig.DbConnection, worldConfig.DbName); + break; + } + default: + throw new Exception("No supported database"); + } + } + + /// + /// 创建一个指定唯一标识的游戏世界实例。 + /// + /// + /// 游戏世界的唯一标识。 + /// 游戏世界实例。 + public static World Create(Scene scene, byte id) + { + if (Worlds.TryGetValue(id, out var world)) + { + return world; + } + + if (!WorldConfigData.Instance.TryGet(id, out var worldConfigData)) + { + return null; + } + + if (string.IsNullOrEmpty(worldConfigData.DbConnection)) + { + return null; + } + + world = new World(scene, id); + Worlds.Add(id, world); + return world; + } + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/World.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/World.cs.meta new file mode 100644 index 00000000..00bf0522 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataBase/World.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6f02362ef34274e508386e3cdc247927 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure.meta new file mode 100644 index 00000000..9aa09d41 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: afe876696fb5f4779abe3289a3bf4f9f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection.meta new file mode 100644 index 00000000..04e1280a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0b3d477f03f404310b5ad48f89d1f193 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/CircularBuffer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/CircularBuffer.cs new file mode 100644 index 00000000..d80ec552 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/CircularBuffer.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Generic; +using System.IO; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.DataStructure.Collection +{ + /// 环形缓存(自增式缓存,自动扩充、不会收缩缓存、所以不要用这个操作过大的IO流) + /// 1、环大小8192,溢出的会自动增加环的大小。 + /// 2、每个块都是一个环形缓存,当溢出的时候会自动添加到下一个环中。 + /// 3、当读取完成后用过的环会放在缓存中,不会销毁掉。 + /// + /// 自增式缓存类,继承自 Stream 和 IDisposable 接口。 + /// 环形缓存具有自动扩充的特性,但不会收缩,适用于操作不过大的 IO 流。 + /// + public sealed class CircularBuffer : Stream, IDisposable + { + private byte[] _lastBuffer; + /// + /// 环形缓存块的默认大小 + /// + public const int ChunkSize = 8192; + private readonly Queue _bufferCache = new Queue(); + private readonly Queue _bufferQueue = new Queue(); + /// + /// 获取或设置环形缓存的第一个索引位置 + /// + public int FirstIndex { get; set; } + /// + /// 获取或设置环形缓存的最后一个索引位置 + /// + public int LastIndex { get; set; } + /// + /// 获取环形缓存的总长度 + /// + public override long Length + { + get + { + if (_bufferQueue.Count == 0) + { + return 0; + } + + return (_bufferQueue.Count - 1) * ChunkSize + LastIndex - FirstIndex; + } + } + + /// + /// 获取环形缓存的第一个块 + /// + public byte[] First + { + get + { + if (_bufferQueue.Count == 0) + { + AddLast(); + } + + return _bufferQueue.Peek(); + } + } + + /// + /// 获取环形缓存的最后一个块 + /// + public byte[] Last + { + get + { + if (_bufferQueue.Count == 0) + { + AddLast(); + } + + return _lastBuffer; + } + } + /// + /// 向环形缓存中添加一个新的块 + /// + public void AddLast() + { + var buffer = _bufferCache.Count > 0 ? _bufferCache.Dequeue() : new byte[ChunkSize]; + _bufferQueue.Enqueue(buffer); + _lastBuffer = buffer; + } + /// + /// 从环形缓存中移除第一个块 + /// + public void RemoveFirst() + { + _bufferCache.Enqueue(_bufferQueue.Dequeue()); + } + + /// + /// 从流中读取指定数量的数据到缓存。 + /// + /// 源数据流。 + /// 要读取的字节数。 + public void Read(Stream stream, int count) + { + if (count > Length) + { + throw new Exception($"bufferList length < count, {Length} {count}"); + } + + var copyCount = 0; + while (copyCount < count) + { + var n = count - copyCount; + if (ChunkSize - FirstIndex > n) + { + stream.Write(First, FirstIndex, n); + FirstIndex += n; + copyCount += n; + } + else + { + stream.Write(First, FirstIndex, ChunkSize - FirstIndex); + copyCount += ChunkSize - FirstIndex; + FirstIndex = 0; + RemoveFirst(); + } + } + } + + /// + /// 从缓存中读取指定数量的数据到内存。 + /// + /// 目标内存。 + /// 要读取的字节数。 + public void Read(Memory memory, int count) + { + if (count > Length) + { + throw new Exception($"bufferList length < count, {Length} {count}"); + } + + var copyCount = 0; + while (copyCount < count) + { + var n = count - copyCount; + var asMemory = First.AsMemory(); + + if (ChunkSize - FirstIndex > n) + { + var slice = asMemory.Slice(FirstIndex, n); + slice.CopyTo(memory.Slice(copyCount, n)); + FirstIndex += n; + copyCount += n; + } + else + { + var length = ChunkSize - FirstIndex; + var slice = asMemory.Slice(FirstIndex, length); + slice.CopyTo(memory.Slice(copyCount, length)); + copyCount += ChunkSize - FirstIndex; + FirstIndex = 0; + RemoveFirst(); + } + } + } + + /// + /// 从自定义流中读取数据到指定的缓冲区。 + /// + /// 目标缓冲区,用于存储读取的数据。 + /// 目标缓冲区中的起始偏移量。 + /// 要读取的字节数。 + /// 实际读取的字节数。 + public override int Read(byte[] buffer, int offset, int count) + { + if (buffer.Length < offset + count) + { + throw new Exception($"buffer length < count, buffer length: {buffer.Length} {offset} {count}"); + } + + var length = Length; + if (length < count) + { + count = (int) length; + } + + var copyCount = 0; + + // 循环直到成功读取所需的字节数 + while (copyCount < count) + { + var copyLength = count - copyCount; + + if (ChunkSize - FirstIndex > copyLength) + { + // 将数据从当前块的缓冲区复制到目标缓冲区 + Array.Copy(First, FirstIndex, buffer, copyCount + offset, copyLength); + + FirstIndex += copyLength; + copyCount += copyLength; + continue; + } + + // 复制当前块中剩余的数据,并切换到下一个块 + Array.Copy(First, FirstIndex, buffer, copyCount + offset, ChunkSize - FirstIndex); + copyCount += ChunkSize - FirstIndex; + FirstIndex = 0; + + RemoveFirst(); + } + + return count; + } + + /// + /// 将数据从给定的字节数组写入流中。 + /// + /// 包含要写入的数据的字节数组。 + public void Write(byte[] buffer) + { + Write(buffer, 0, buffer.Length); + } + + /// + /// 将数据从给定的流写入流中。 + /// + /// 包含要写入的数据的流。 + public void Write(Stream stream) + { + var copyCount = 0; + var count = (int) (stream.Length - stream.Position); + + while (copyCount < count) + { + if (LastIndex == ChunkSize) + { + AddLast(); + LastIndex = 0; + } + + var n = count - copyCount; + + if (ChunkSize - LastIndex > n) + { + _ = stream.Read(Last, LastIndex, n); + LastIndex += count - copyCount; + copyCount += n; + } + else + { + _ = stream.Read(Last, LastIndex, ChunkSize - LastIndex); + copyCount += ChunkSize - LastIndex; + LastIndex = ChunkSize; + } + } + } + + /// + /// 将数据从给定的字节数组写入流中。 + /// + /// 包含要写入的数据的字节数组。 + /// 开始写入的缓冲区中的索引。 + /// 要写入的字节数。 + public override void Write(byte[] buffer, int offset, int count) + { + var copyCount = 0; + + while (copyCount < count) + { + if (ChunkSize == LastIndex) + { + AddLast(); + LastIndex = 0; + } + + var byteLength = count - copyCount; + + if (ChunkSize - LastIndex > byteLength) + { + Array.Copy(buffer, copyCount + offset, Last, LastIndex, byteLength); + LastIndex += byteLength; + copyCount += byteLength; + } + else + { + Array.Copy(buffer, copyCount + offset, Last, LastIndex, ChunkSize - LastIndex); + copyCount += ChunkSize - LastIndex; + LastIndex = ChunkSize; + } + } + } + + /// + /// 获取一个值,指示流是否支持读取操作。 + /// + public override bool CanRead { get; } = true; + /// + /// 获取一个值,指示流是否支持寻找操作。 + /// + public override bool CanSeek { get; } = false; + /// + /// 获取一个值,指示流是否支持写入操作。 + /// + public override bool CanWrite { get; } = true; + /// + /// 获取或设置流中的位置。 + /// + public override long Position { get; set; } + + /// + /// 刷新流(在此实现中引发未实现异常)。 + /// + public override void Flush() + { + throw new NotImplementedException(); + } + + /// + /// 在流中寻找特定位置(在此实现中引发未实现异常)。 + /// + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotImplementedException(); + } + + /// + /// 设置流的长度(在此实现中引发未实现异常)。 + /// + public override void SetLength(long value) + { + throw new NotImplementedException(); + } + + /// + /// 释放 CustomStream 使用的所有资源。 + /// + public new void Dispose() + { + _bufferQueue.Clear(); + _lastBuffer = null; + FirstIndex = 0; + LastIndex = 0; + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/CircularBuffer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/CircularBuffer.cs.meta new file mode 100644 index 00000000..ee284a26 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/CircularBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38264758f23d1448a975efc4f4b7da63 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs new file mode 100644 index 00000000..e110a0b3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs @@ -0,0 +1,197 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 并发的一对多列表池,用于维护具有相同键的多个值的关联关系,实现了 接口。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyListPool : ConcurrentOneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 的实例。 + /// + /// 创建的实例。 + public static ConcurrentOneToManyListPool Create() + { + var a = MultiThreadPool.Rent>(); + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + // 清空实例的数据 + Clear(); + // 将实例返回到池中以便重用 + MultiThreadPool.Return(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 并发的一对多列表,用于维护具有相同键的多个值的关联关系。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyList : ConcurrentDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit = 120; + + /// + /// 初始化 类的新实例。 + /// + public ConcurrentOneToManyList() + { + } + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public ConcurrentOneToManyList(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定键的列表是否包含指定值。 + /// + /// 要搜索的键。 + /// 要搜索的值。 + /// 如果列表包含值,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 向指定键的列表中添加一个值。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + base[key] = list; + return; + } + + list.Add(value); + } + + /// + /// 获取指定键的列表中的第一个值。 + /// + /// 要获取第一个值的键。 + /// 指定键的列表中的第一个值,如果不存在则为默认值。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + + /// + /// 从指定键的列表中移除一个值。 + /// + /// 要移除值的键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + + /// + /// 从字典中移除指定键以及其关联的列表。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryRemove(key, out var list)) return; + + Recycle(list); + } + + /// + /// 从队列中获取一个列表,如果队列为空则创建一个新的列表。 + /// + /// 获取的列表。 + private List Fetch() + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + + /// + /// 将一个列表回收到队列中。 + /// + /// 要回收的列表。 + private void Recycle(List list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空当前类的数据,包括从基类继承的数据以及自定义的数据队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta new file mode 100644 index 00000000..3b3b7d2b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 21b2d3135b133441aa08c5eb1768a103 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs new file mode 100644 index 00000000..59c43670 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs @@ -0,0 +1,194 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 表示一个并发的一对多队列池,用于维护具有相同键的多个值的关联关系,实现了 接口。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyQueuePool : ConcurrentOneToManyQueue, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建并返回一个 的实例。 + /// + /// 创建的实例。 + public static ConcurrentOneToManyQueuePool Create() + { + var a = MultiThreadPool.Rent>(); + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); + // 将实例返回到对象池中,以便重用 + MultiThreadPool.Return(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 表示一个并发的一对多队列,用于维护具有相同键的多个值的关联关系。 + /// + /// 关键字的类型,不能为空。 + /// 值的类型。 + public class ConcurrentOneToManyQueue : ConcurrentDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit; + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public ConcurrentOneToManyQueue(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定键的队列是否包含指定值。 + /// + /// 要搜索的键。 + /// 要搜索的值。 + /// 如果队列包含值,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 向指定键的队列中添加一个值。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Enqueue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Enqueue(value); + TryAdd(key, list); + return; + } + + list.Enqueue(value); + } + + /// + /// 从指定键的队列中出队并返回一个值。 + /// + /// 要出队的键。 + /// 出队的值,如果队列为空则为默认值。 + public TValue Dequeue(TKey key) + { + if (!TryGetValue(key, out var list) || list.Count == 0) return default; + + var value = list.Dequeue(); + + if (list.Count == 0) RemoveKey(key); + + return value; + } + + /// + /// 尝试从指定键的队列中出队一个值。 + /// + /// 要出队的键。 + /// 出队的值,如果队列为空则为默认值。 + /// 如果成功出队,则为 true;否则为 false。 + public bool TryDequeue(TKey key, out TValue value) + { + value = Dequeue(key); + + return value != null; + } + + /// + /// 从字典中移除指定键以及其关联的队列。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + TryRemove(key, out _); + Recycle(list); + } + + /// + /// 从队列中获取一个新的队列,如果队列为空则创建一个新的队列。 + /// + /// 获取的队列。 + private Queue Fetch() + { + return _queue.Count <= 0 ? new Queue() : _queue.Dequeue(); + } + + /// + /// 将一个队列回收到队列池中。 + /// + /// 要回收的队列。 + private void Recycle(Queue list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空当前类的数据,包括从基类继承的键值对字典中的数据以及自定义的队列池。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta new file mode 100644 index 00000000..1497661d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ConcurrentOneToManyQueuePool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 50a0f004d8b7b4075a4ce01376e49375 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/HashSetPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/HashSetPool.cs new file mode 100644 index 00000000..bb64ae87 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/HashSetPool.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可释放的哈希集合对象池。 + /// + /// 哈希集合中元素的类型。 + public sealed class HashSetPool : HashSet, IDisposable, IPool + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 创建一个 哈希集合池的实例。 + /// + /// 创建的实例。 + public static HashSetPool Create() + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); + list._isDispose = false; + list._isPool = true; + return list; +#else + var list = MultiThreadPool.Rent>(); + list._isDispose = false; + list._isPool = true; + return list; +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基本哈希集合对象池,他自持有实际的哈希集合。 + /// + /// 哈希集合中元素的类型。 + public sealed class HashSetBasePool : IDisposable, IPool + { + private bool _isPool; + + /// + /// 存储实际的哈希集合 + /// + public HashSet Set = new HashSet(); + + /// + /// 创建一个 基本哈希集合对象池的实例。 + /// + /// 创建的实例。 + public static HashSetBasePool Create() + { +#if FANTASY_WEBGL + var hashSetBasePool = Pool>.Rent(); + hashSetBasePool._isPool = true; + return hashSetBasePool; +#else + var hashSetBasePool = MultiThreadPool.Rent>(); + hashSetBasePool._isPool = true; + return hashSetBasePool; +#endif + } + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + Set.Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/HashSetPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/HashSetPool.cs.meta new file mode 100644 index 00000000..27aadf41 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/HashSetPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c49468bddc6524c419ace92b9ad68a5d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ListPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ListPool.cs new file mode 100644 index 00000000..de70fe23 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ListPool.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可释放的列表(List)对象池。 + /// + /// 列表中元素的类型。 + public sealed class ListPool : List, IDisposable, IPool + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 使用指定的元素创建一个 列表(List)对象池的实例。 + /// + /// 要添加到列表的元素。 + /// 创建的实例。 + public static ListPool Create(params T[] args) + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + + if (args != null) + { + list.AddRange(args); + } + + return list; + } + + /// + /// 使用指定的列表创建一个 列表(List)对象池的实例。 + /// + /// 要添加到列表的元素列表。 + /// 创建的实例。 + public static ListPool Create(List args) + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + + if (args != null) + { + list.AddRange(args); + } + + return list; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ListPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ListPool.cs.meta new file mode 100644 index 00000000..5827c4a1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f629886e3686046c6b00225679a7dbf5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyHashSetPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyHashSetPool.cs new file mode 100644 index 00000000..8a5766c2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyHashSetPool.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 一对多哈希集合(OneToManyHashSet)对象池。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyHashSetPool : OneToManyHashSet, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 一对多哈希集合(OneToManyHashSet)对象池的实例。 + /// + /// 创建的实例。 + public static OneToManyHashSetPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多哈希集合(OneToManyHashSet),用于创建和管理键对应多个值的集合。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyHashSet : Dictionary> where TKey : notnull + { + /// 用于回收和重用的空闲值集合队列。 + private readonly Queue> _queue = new Queue>(); + /// 设置最大回收限制,用于控制值集合的最大数量。 + private readonly int _recyclingLimit = 120; + /// 一个空的、不包含任何元素的哈希集合,用于在查找失败时返回。 + private static HashSet _empty = new HashSet(); + + /// + /// 初始化 类的新实例。 + /// + public OneToManyHashSet() { } + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyHashSet(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定的键值对是否存在于集合中。 + /// + /// 键。 + /// 值。 + /// 如果存在则为 true,否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 添加指定的键值对到集合中。 + /// + /// 键。 + /// 值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + Add(key, list); + + return; + } + + list.Add(value); + } + + /// + /// 从集合中移除指定键对应的值。 + /// + /// 键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + + /// + /// 从集合中移除指定键及其对应的值集合。 + /// + /// 键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + Recycle(list); + } + + /// + /// 获取指定键对应的值集合,如果不存在则返回一个空的哈希集合。 + /// + /// 键。 + /// 对应的值集合或空的哈希集合。 + public HashSet GetValue(TKey key) + { + if (TryGetValue(key, out HashSet value)) + { + return value; + } + + return _empty; + } + + /// + /// 从队列中获取一个空闲的值集合,或者创建一个新的。 + /// + /// 值集合。 + private HashSet Fetch() + { + return _queue.Count <= 0 ? new HashSet() : _queue.Dequeue(); + } + + /// + /// 回收值集合到队列中,以便重复利用。 + /// + /// 要回收的值集合。 + private void Recycle(HashSet list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空集合中的数据并和队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta new file mode 100644 index 00000000..445c83d0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyHashSetPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e0cac58c09d6429faba279d03ef2317 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyListPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyListPool.cs new file mode 100644 index 00000000..80568efe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyListPool.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可回收的、一对多关系的列表池。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyListPool : OneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 一对多关系的列表池的实例。 + /// + /// 创建的实例。 + public static OneToManyListPool Create() + { +#if FANTASY_WEBGL || FANTASY_EXPORTER + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + return list; + } + + /// + /// 释放当前对象所占用的资源,并将对象回收到对象池中。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL || FANTASY_EXPORTER + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多关系的列表字典。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyList : Dictionary> where TKey : notnull + { + private readonly int _recyclingLimit = 120; + private static readonly List Empty = new List(); + private readonly Queue> _queue = new Queue>(); + + /// + /// 初始化一个新的 实例。 + /// + public OneToManyList() { } + + /// + /// 设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyList(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断给定的键和值是否存在于列表中。 + /// + /// 要搜索的键。 + /// 要搜索的值。 + /// 如果存在则为 ,否则为 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 向列表中添加指定键和值。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + Add(key, list); + + return; + } + + list.Add(value); + } + + /// + /// 获取指定键对应的列表中的第一个值。 + /// + /// 要获取值的键。 + /// 键对应的列表中的第一个值。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + + /// + /// 从列表中移除指定键和值。 + /// + /// 要移除值的键。 + /// 要移除的值。 + /// 如果成功移除则为 ,否则为 + public bool RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + return true; + } + + var isRemove = list.Remove(value); + + if (list.Count == 0) + { + isRemove = RemoveByKey(key); + } + + return isRemove; + } + + /// + /// 从列表中移除指定键及其关联的所有值。 + /// + /// 要移除的键。 + /// 如果成功移除则为 ,否则为 + public bool RemoveByKey(TKey key) + { + if (!TryGetValue(key, out var list)) + { + return false; + } + + Remove(key); + Recycle(list); + return true; + } + + /// + /// 获取指定键关联的所有值的列表。 + /// + /// 要获取值的键。 + /// 键关联的所有值的列表。 + public List GetValues(TKey key) + { + if (TryGetValue(key, out List list)) + { + return list; + } + + return Empty; + } + + /// + /// 清除字典中的所有键值对,并回收相关的值集合。 + /// + public new void Clear() + { + foreach (var keyValuePair in this) Recycle(keyValuePair.Value); + + base.Clear(); + } + + /// + /// 从空闲值集合队列中获取一个值集合,如果队列为空则创建一个新的值集合。 + /// + /// 从队列中获取的值集合。 + private List Fetch() + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + + /// + /// 回收一个不再使用的值集合到空闲值集合队列中。 + /// + /// 要回收的值集合。 + private void Recycle(List list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyListPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyListPool.cs.meta new file mode 100644 index 00000000..b1bbb98c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c48383c842aa40b683f03b79f845932 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyQueuePool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyQueuePool.cs new file mode 100644 index 00000000..222576e4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyQueuePool.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 支持一对多关系的队列池,用于存储具有相同键的值的队列集合。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyQueuePool : OneToManyQueue, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 一对多关系的队列池的实例。 + /// + /// 创建的实例。 + public static OneToManyQueuePool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例所占用的资源,并将实例回收到对象池中。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 支持一对多关系的队列,用于存储具有相同键的值的队列集合。 + /// + /// 键的类型。 + /// 值的类型。 + public class OneToManyQueue : Dictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit; + + /// + /// 创建一个 一对多关系的队列的实例。设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyQueue(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断指定键的值队列是否包含指定的值。 + /// + /// 要查找的键。 + /// 要查找的值。 + /// 如果存在,则为 true;否则为 false + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 将指定的值添加到指定键的值队列中。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Enqueue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Enqueue(value); + Add(key, list); + return; + } + + list.Enqueue(value); + } + + /// + /// 从指定键的值队列中出队一个值。 + /// + /// 要出队的键。 + /// 出队的值。 + public TValue Dequeue(TKey key) + { + if (!TryGetValue(key, out var list) || list.Count == 0) + { + return default; + } + + var value = list.Dequeue(); + + if (list.Count == 0) + { + RemoveKey(key); + } + + return value; + } + + /// + /// 尝试从指定键的值队列中出队一个值。 + /// + /// 要出队的键。 + /// 出队的值。 + /// 如果成功出队,则为 true;否则为 false + public bool TryDequeue(TKey key, out TValue value) + { + value = Dequeue(key); + + return value != null; + } + + /// + /// 从字典中移除指定键及其对应的值队列。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + Recycle(list); + } + + /// + /// 从队列池中获取一个值队列。如果队列池为空,则创建一个新的值队列。 + /// + /// 获取的值队列。 + private Queue Fetch() + { + return _queue.Count <= 0 ? new Queue() : _queue.Dequeue(); + } + + /// + /// 回收一个不再使用的值队列到队列池中,以便重用。 + /// + /// 要回收的值队列。 + private void Recycle(Queue list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 清空当前实例的数据,同时回收所有值队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta new file mode 100644 index 00000000..b90e2c13 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/OneToManyQueuePool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b6455b3359394987af4c0a4855189e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ReuseList.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ReuseList.cs new file mode 100644 index 00000000..b4395e8a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ReuseList.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 可重用的列表,继承自 类。该类支持通过对象池重用列表实例,以减少对象分配和释放的开销。 + /// + /// 列表中元素的类型。 + public sealed class ReuseList : List, IDisposable, IPool + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 可重用的列表的实例。 + /// + /// 创建的实例。 + public static ReuseList Create() + { +#if FANTASY_WEBGL + var list = Pool>.Rent(); +#else + var list = MultiThreadPool.Rent>(); +#endif + list._isDispose = false; + list._isPool = true; + return list; + } + + /// + /// 释放该实例所占用的资源,并将实例返回到对象池中,以便重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ReuseList.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ReuseList.cs.meta new file mode 100644 index 00000000..1b600f72 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/ReuseList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9826877496b99479892a7359519298d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs new file mode 100644 index 00000000..464ab58e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs @@ -0,0 +1,226 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 基于排序字典和并发集合实现的一对多映射列表的对象池包装类,继承自 类, + /// 同时实现了 接口,以支持对象的重用和释放。 + /// + /// 键的类型。 + /// 值的类型。 + public class SortedConcurrentOneToManyListPool : SortedConcurrentOneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例,使用默认的参数设置。 + /// + /// 新创建的 实例。 + public static SortedConcurrentOneToManyListPool Create() + { + var a = MultiThreadPool.Rent>(); + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前对象池实例,将其返回到对象池以供重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); + MultiThreadPool.Return(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基于排序字典和并发集合实现的一多对映射列表类,继承自 类, + /// 用于在多个值与一个键关联的情况下进行管理和存储。该类支持并发操作,适用于多线程环境。 + /// + /// 键的类型。 + /// 值的类型。 + public class SortedConcurrentOneToManyList : SortedDictionary> where TKey : notnull + { + /// 用于同步操作的锁对象,它确保在多线程环境下对数据的安全访问。 + private readonly object _lockObject = new object(); + /// 用于存储缓存的队列。 + private readonly Queue> _queue = new Queue>(); + /// 控制缓存回收的限制。当缓存的数量超过此限制时,旧的缓存将会被回收。 + private readonly int _recyclingLimit; + + /// + /// 初始化一个新的 类的实例,使用默认的参数设置。 + /// + public SortedConcurrentOneToManyList() + { + } + + /// + /// 初始化一个新的 类的实例,指定最大缓存数量。 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public SortedConcurrentOneToManyList(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 检查指定的键和值是否存在于映射列表中。 + /// + /// 要检查的键。 + /// 要检查的值。 + /// 如果存在,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + lock (_lockObject) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + } + + /// + /// 将指定的值添加到与指定键关联的列表中。 + /// + /// 要关联值的键。 + /// 要添加到列表的值。 + public void Add(TKey key, TValue value) + { + lock (_lockObject) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + base[key] = list; + return; + } + + list.Add(value); + } + } + + /// + /// 获取与指定键关联的列表中的第一个值。 + /// 如果列表不存在或为空,则返回默认值。 + /// + /// 要获取第一个值的键。 + /// 第一个值,或默认值。 + public TValue First(TKey key) + { + lock (_lockObject) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + } + + /// + /// 从与指定键关联的列表中移除指定的值。 + /// 如果列表不存在或值不存在于列表中,则不执行任何操作。 + /// + /// 要移除值的键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + lock (_lockObject) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + } + + /// + /// 从映射列表中移除指定的键及其关联的列表。 + /// 如果键不存在于映射列表中,则不执行任何操作。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + lock (_lockObject) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + + Recycle(list); + } + } + + /// + /// 从缓存中获取一个可重用的列表。如果缓存中不存在列表,则创建一个新的列表并返回。 + /// + /// 可重用的列表。 + private List Fetch() + { + lock (_lockObject) + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + } + + /// + /// 将不再使用的列表回收到缓存中,以便重复利用。如果缓存数量超过限制,则丢弃列表而不进行回收。 + /// + /// 要回收的列表。 + private void Recycle(List list) + { + lock (_lockObject) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + } + + /// + /// 清空映射列表以及队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta new file mode 100644 index 00000000..2ca59b28 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedConcurrentOneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fef1d9dea81914fcf9fc9f5b1e5989d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs new file mode 100644 index 00000000..8158db56 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 基于排序字典实现的一对多关系的映射哈希集合的对象池包装类,将唯一键映射到多个值的哈希集合。 + /// 同时实现了 接口,以支持对象的重用和释放。 + /// + /// 字典中键的类型。 + /// 哈希集合中值的类型。 + public class SortedOneToManyHashSetPool : SortedOneToManyHashSet, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 实例。 + /// + /// 新创建的实例。 + public static SortedOneToManyHashSetPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前对象池实例,将其返回到对象池以供重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基于排序字典实现的一对多关系的映射哈希集合类,将唯一键映射到多个值的哈希集合。 + /// 用于在多个值与一个键关联的情况下进行管理和存储。 + /// + /// 字典中键的类型。 + /// 集合中值的类型。 + public class SortedOneToManyHashSet : SortedDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit = 120; + + /// + /// 创建一个新的 实例。 + /// + public SortedOneToManyHashSet() { } + + /// + /// 创建一个新的 实例,设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public SortedOneToManyHashSet(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断哈希集合中是否包含指定的键值对。 + /// + /// 要查找的键。 + /// 要查找的值。 + /// 如果键值对存在,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 将指定值添加到给定键关联的哈希集合中。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + Add(key, list); + + return; + } + + list.Add(value); + } + + /// + /// 从指定键关联的哈希集合中移除特定值。 + /// 如果哈希集合不存在或值不存在于集合中,则不执行任何操作。 + /// + /// 要移除值的键。 + /// 要移除的值。 + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) return; + + list.Remove(value); + + if (list.Count == 0) RemoveKey(key); + } + + /// + /// 从字典中移除指定键以及关联的哈希集合,并将集合进行回收。 + /// 如果键不存在于映射列表中,则不执行任何操作。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) return; + + Remove(key); + + Recycle(list); + } + + /// + /// 获取一个空的或回收的哈希集合。 + /// + /// 获取的哈希集合实例。 + private HashSet Fetch() + { + return _queue.Count <= 0 ? new HashSet() : _queue.Dequeue(); + } + + /// + /// 回收一个哈希集合,将其清空并放入回收队列中。 + /// + /// 要回收的哈希集合。 + private void Recycle(HashSet list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(list); + } + + /// + /// 重写 Clear 方法,清空字典并清空回收队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta new file mode 100644 index 00000000..13e463b7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyHashSetPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fe9032846c3f4a11be30459a9e12d7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyListPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyListPool.cs new file mode 100644 index 00000000..f0bae12f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyListPool.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 + +namespace Fantasy.DataStructure.Collection +{ + /// + /// 基于排序字典实现的一对多映射列表的对象池包装类,继承自 类, + /// 同时实现了 接口,以支持对象的重用和释放。 + /// + /// 字典中键的类型。 + /// 列表中值的类型。 + public class SortedOneToManyListPool : SortedOneToManyList, IDisposable, IPool where TKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 实例。 + /// + /// 新创建的实例。 + public static SortedOneToManyListPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前对象池实例,将其返回到对象池以供重用。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 基于排序字典实现的一对多关系的映射列表类,将唯一键映射到包含多个值的列表。 + /// 用于在多个值与一个键关联的情况下进行管理和存储。 + /// + /// 字典中键的类型。 + /// 列表中值的类型。 + public class SortedOneToManyList : SortedDictionary> where TKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit; + + /// + /// 创建一个新的 实例。 + /// + public SortedOneToManyList() + { + } + + /// + /// 创建一个新的 实例,设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public SortedOneToManyList(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 判断列表中是否包含指定的键值对。 + /// + /// 要查找的键。 + /// 要查找的值。 + /// 如果键值对存在,则为 true;否则为 false。 + public bool Contains(TKey key, TValue value) + { + TryGetValue(key, out var list); + + return list != null && list.Contains(value); + } + + /// + /// 将指定值添加到给定键关联的列表中。 + /// + /// 要添加值的键。 + /// 要添加的值。 + public void Add(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + list = Fetch(); + list.Add(value); + base[key] = list; + return; + } + + list.Add(value); + } + + /// + /// 获取指定键关联的列表中的第一个值。 + /// + /// 要查找值的键。 + /// 指定键关联的列表中的第一个值,如果列表为空则返回默认值。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var list) ? default : list.FirstOrDefault(); + } + + /// + /// 从指定键关联的列表中移除特定值。 + /// + /// 要移除值的键。 + /// 要移除的值。 + + public void RemoveValue(TKey key, TValue value) + { + if (!TryGetValue(key, out var list)) + { + return; + } + + list.Remove(value); + + if (list.Count == 0) + { + RemoveKey(key); + } + } + + /// + /// 从字典中移除指定键以及关联的列表,并将列表进行回收。 + /// + /// 要移除的键。 + + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) + { + return; + } + + Remove(key); + Recycle(list); + } + + /// + /// 获取一个空的或回收的列表。 + /// + /// 获取的列表实例。 + private List Fetch() + { + return _queue.Count <= 0 ? new List() : _queue.Dequeue(); + } + + /// + /// 回收一个列表,将其清空并放入回收队列中。如果缓存数量超过限制,则丢弃列表而不进行回收 + /// + /// 要回收的列表。 + private void Recycle(List list) + { + list.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) + { + return; + } + + _queue.Enqueue(list); + } + + /// + /// 重写 Clear 方法,清空字典并清空回收队列。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta new file mode 100644 index 00000000..c428dccd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Collection/SortedOneToManyListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e0621d52f951402daa68b108d7129f4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary.meta new file mode 100644 index 00000000..3ffb9668 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4a444c902ff594bbaa3a3fb394e7f53a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryExtensions.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryExtensions.cs new file mode 100644 index 00000000..ed0aa579 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryExtensions.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +#pragma warning disable CS8601 // Possible null reference assignment. + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供对字典的扩展方法。 + /// + public static class DictionaryExtensions + { + /// + /// 尝试从字典中移除指定键,并返回相应的值。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + /// 要操作的字典实例。 + /// 要移除的键。 + /// 从字典中移除的值(如果成功移除)。 + /// 如果成功移除键值对,则为 true;否则为 false。 + public static bool TryRemove(this IDictionary self, T key, out TV value) + { + if (!self.TryGetValue(key, out value)) + { + return false; + } + + self.Remove(key); + return true; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta new file mode 100644 index 00000000..d3c3a07b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6975fd47ec81d474cbd1ba996d01e864 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryPool.cs new file mode 100644 index 00000000..567901c2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryPool.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个可以使用对象池管理的字典类。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + public sealed class DictionaryPool : Dictionary, IDisposable, IPool where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static DictionaryPool Create() + { +#if FANTASY_WEBGL + var dictionary = Pool>.Rent(); +#else + var dictionary = MultiThreadPool.Rent>(); +#endif + dictionary._isDispose = false; + dictionary._isPool = true; + return dictionary; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta new file mode 100644 index 00000000..861c20ad --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 421f6528d2cff461dab994c2f358f24d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs new file mode 100644 index 00000000..e868710c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs @@ -0,0 +1,289 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个双向映射字典对象池类,用于双向键值对映射。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + public class DoubleMapDictionaryPool : DoubleMapDictionary, IDisposable, IPool where TKey : notnull where TValue : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static DoubleMapDictionaryPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 可以实现双向映射的字典类,用于将键和值进行双向映射。 + /// + /// 键的类型,不能为 null。 + /// 值的类型,不能为 null。 + public class DoubleMapDictionary where TK : notnull where TV : notnull + { + private readonly Dictionary _kv = new Dictionary(); + private readonly Dictionary _vk = new Dictionary(); + + /// + /// 创建一个新的空的 实例。 + /// + public DoubleMapDictionary() { } + + /// + /// 创建一个新的具有指定初始容量的 实例。 + /// + /// 初始容量。 + public DoubleMapDictionary(int capacity) + { + _kv = new Dictionary(capacity); + _vk = new Dictionary(capacity); + } + + /// + /// 获取包含字典中所有键的列表。 + /// + public List Keys => new List(_kv.Keys); + + /// + /// 获取包含字典中所有值的列表。 + /// + public List Values => new List(_vk.Keys); + + /// + /// 对字典中的每个键值对执行指定的操作。 + /// + /// 要执行的操作。 + public void ForEach(Action action) + { + if (action == null) + { + return; + } + + var keys = _kv.Keys; + foreach (var key in keys) + { + action(key, _kv[key]); + } + } + + /// + /// 将指定的键值对添加到字典中。 + /// + /// 要添加的键。 + /// 要添加的值。 + public void Add(TK key, TV value) + { + if (key == null || value == null || _kv.ContainsKey(key) || _vk.ContainsKey(value)) + { + return; + } + + _kv.Add(key, value); + _vk.Add(value, key); + } + + /// + /// 根据指定的键获取相应的值。 + /// + /// 要查找值的键。 + /// 与指定键关联的值,如果找不到键,则返回默认值。 + public TV GetValueByKey(TK key) + { + if (key != null && _kv.ContainsKey(key)) + { + return _kv[key]; + } + + return default; + } + + /// + /// 尝试根据指定的键获取相应的值。 + /// + /// 要查找值的键。 + /// 如果找到,则为与指定键关联的值;否则为值的默认值。 + /// 如果找到键,则为 true;否则为 false。 + public bool TryGetValueByKey(TK key, out TV value) + { + var result = key != null && _kv.ContainsKey(key); + + value = result ? _kv[key] : default; + + return result; + } + + /// + /// 根据指定的值获取相应的键。 + /// + /// 要查找键的值。 + /// 与指定值关联的键,如果找不到值,则返回默认键。 + public TK GetKeyByValue(TV value) + { + if (value != null && _vk.ContainsKey(value)) + { + return _vk[value]; + } + + return default; + } + + /// + /// 尝试根据指定的值获取相应的键。 + /// + /// 要查找键的值。 + /// 如果找到,则为与指定值关联的键;否则为键的默认值。 + /// 如果找到值,则为 true;否则为 false。 + public bool TryGetKeyByValue(TV value, out TK key) + { + var result = value != null && _vk.ContainsKey(value); + + key = result ? _vk[value] : default; + + return result; + } + + /// + /// 根据指定的键移除键值对。 + /// + /// 要移除的键。 + public void RemoveByKey(TK key) + { + if (key == null) + { + return; + } + + if (!_kv.TryGetValue(key, out var value)) + { + return; + } + + _kv.Remove(key); + _vk.Remove(value); + } + + /// + /// 根据指定的值移除键值对。 + /// + /// 要移除的值。 + public void RemoveByValue(TV value) + { + if (value == null) + { + return; + } + + if (!_vk.TryGetValue(value, out var key)) + { + return; + } + + _kv.Remove(key); + _vk.Remove(value); + } + + /// + /// 清空字典中的所有键值对。 + /// + public void Clear() + { + _kv.Clear(); + _vk.Clear(); + } + + /// + /// 判断字典是否包含指定的键。 + /// + /// 要检查的键。 + /// 如果字典包含指定的键,则为 true;否则为 false。 + public bool ContainsKey(TK key) + { + return key != null && _kv.ContainsKey(key); + } + + /// + /// 判断字典是否包含指定的值。 + /// + /// 要检查的值。 + /// 如果字典包含指定的值,则为 true;否则为 false。 + public bool ContainsValue(TV value) + { + return value != null && _vk.ContainsKey(value); + } + + /// + /// 判断字典是否包含指定的键值对。 + /// + /// 要检查的键。 + /// 要检查的值。 + /// 如果字典包含指定的键值对,则为 true;否则为 false。 + public bool Contains(TK key, TV value) + { + if (key == null || value == null) + { + return false; + } + + return _kv.ContainsKey(key) && _vk.ContainsKey(value); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta new file mode 100644 index 00000000..a0beca03 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/DoubleMapDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a23375ac49ac64827a5d2e6ae476bbab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/EntityDictionary.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/EntityDictionary.cs new file mode 100644 index 00000000..fc4d44f8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/EntityDictionary.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个带资源释放功能的实体字典类,支持使用对象池管理。 + /// + /// 字典中键的类型。 + /// 字典中值的类型,必须实现 IDisposable 接口。 + public sealed class EntityDictionary : Dictionary, IDisposable, IPool where TN : IDisposable where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static EntityDictionary Create() + { +#if FANTASY_WEBGL + var entityDictionary = Pool>.Rent(); +#else + var entityDictionary = MultiThreadPool.Rent>(); +#endif + entityDictionary._isDispose = false; + entityDictionary._isPool = true; + return entityDictionary; + } + + /// + /// 清空字典中的所有键值对,并释放值的资源。 + /// + public new void Clear() + { + foreach (var keyValuePair in this) + { + keyValuePair.Value.Dispose(); + } + + base.Clear(); + } + + /// + /// 清空字典中的所有键值对,但不释放值的资源。 + /// + public void ClearNotDispose() + { + base.Clear(); + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta new file mode 100644 index 00000000..35b066a5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/EntityDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 30708df4a385e4aee83551b3371240fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs new file mode 100644 index 00000000..05154232 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Fantasy.Pool; + +#pragma warning disable CS8603 +#pragma warning disable CS8601 + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 一对多映射关系的字典对象池。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的键类型。 + /// 内部字典中的值类型。 + public class OneToManyDictionaryPool : OneToManyDictionary, IDisposable, IPool where TKey : notnull where TValueKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 的实例。 + /// + /// 新创建的 OneToManyDictionaryPool 实例。 + public static OneToManyDictionaryPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例及其资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多映射关系的字典。每个键都对应一个内部字典,该内部字典将键值映射到相应的值。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的键类型。 + /// 内部字典中的值类型。 + public class OneToManyDictionary : Dictionary> + where TKey : notnull where TValueKey : notnull + { + private readonly Queue> _queue = new Queue>(); + private readonly int _recyclingLimit = 120; + + /// + /// 创建一个新的 实例。 + /// + public OneToManyDictionary() { } + + /// + /// 创建一个新的 实例,并指定最大缓存数量。 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManyDictionary(int recyclingLimit = 0) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 检查是否包含指定的键值对。 + /// + /// 外部字典中的键。 + /// 内部字典中的键。 + /// 如果包含指定的键值对,则为 true;否则为 false。 + public bool Contains(TKey key, TValueKey valueKey) + { + TryGetValue(key, out var dic); + + return dic != null && dic.ContainsKey(valueKey); + } + + /// + /// 尝试获取指定键值对的值。 + /// + /// 外部字典中的键。 + /// 内部字典中的键。 + /// 获取的值,如果操作成功,则为值;否则为默认值。 + /// 如果操作成功,则为 true;否则为 false。 + public bool TryGetValue(TKey key, TValueKey valueKey, out TValue value) + { + value = default; + return TryGetValue(key, out var dic) && dic.TryGetValue(valueKey, out value); + } + + /// + /// 获取指定键的第一个值。 + /// + /// 要获取第一个值的键。 + public TValue First(TKey key) + { + return !TryGetValue(key, out var dic) ? default : dic.First().Value; + } + + /// + /// 向字典中添加指定的键值对。 + /// + /// 要添加键值对的键。 + /// 要添加键值对的内部字典键。 + /// 要添加的值。 + public void Add(TKey key, TValueKey valueKey, TValue value) + { + if (!TryGetValue(key, out var dic)) + { + dic = Fetch(); + dic[valueKey] = value; + // dic.Add(valueKey, value); + Add(key, dic); + + return; + } + + dic[valueKey] = value; + // dic.Add(valueKey, value); + } + + /// + /// 从字典中移除指定的键值对。 + /// + /// 要移除键值对的键。 + /// 要移除键值对的内部字典键。 + /// 如果成功移除键值对,则为 true;否则为 false。 + public bool Remove(TKey key, TValueKey valueKey) + { + if (!TryGetValue(key, out var dic)) return false; + + var result = dic.Remove(valueKey); + + if (dic.Count == 0) RemoveKey(key); + + return result; + } + + /// + /// 从字典中移除指定的键值对。 + /// + /// 要移除键值对的键。 + /// 要移除键值对的内部字典键。 + /// 如果成功移除键值对,则为移除的值;否则为默认值。 + /// 如果成功移除键值对,则为 true;否则为 false。 + public bool Remove(TKey key, TValueKey valueKey, out TValue value) + { + if (!TryGetValue(key, out var dic)) + { + value = default; + return false; + } + + var result = dic.TryGetValue(valueKey, out value); + + if (result) dic.Remove(valueKey); + + if (dic.Count == 0) RemoveKey(key); + + return result; + } + + /// + /// 移除字典中的指定键及其相关的所有键值对。 + /// + /// 要移除的键。 + public void RemoveKey(TKey key) + { + if (!TryGetValue(key, out var dic)) return; + + Remove(key); + Recycle(dic); + } + + /// + /// 从对象池中获取一个内部字典实例,如果池中没有,则创建一个新实例。 + /// + /// 获取的内部字典实例。 + private Dictionary Fetch() + { + return _queue.Count <= 0 ? new Dictionary() : _queue.Dequeue(); + } + + /// + /// 将不再使用的内部字典实例放回对象池中,以便后续重用。 + /// + /// 要放回对象池的内部字典实例。 + private void Recycle(Dictionary dic) + { + dic.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) return; + + _queue.Enqueue(dic); + } + + /// + /// 清空字典中的所有键值对,并将不再使用的内部字典实例放回对象池中。 + /// + public new void Clear() + { + foreach (var keyValuePair in this) Recycle(keyValuePair.Value); + + base.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta new file mode 100644 index 00000000..7db27faa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManyDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4cd83a6bbc1914aa4bf1f94f1cba1c47 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs new file mode 100644 index 00000000..127a8ac6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8601 + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 一对多映射关系的排序字典对象池。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的排序键类型。 + /// 内部字典中的值类型。 + public class OneToManySortedDictionaryPool : OneToManySortedDictionary, IDisposable, IPool where TKey : notnull where TSortedKey : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个 的实例。 + /// + /// 新创建的 OneToManySortedDictionaryPool 实例。 + public static OneToManySortedDictionaryPool Create() + { +#if FANTASY_WEBGL + var a = Pool>.Rent(); +#else + var a = MultiThreadPool.Rent>(); +#endif + a._isDispose = false; + a._isPool = true; + return a; + } + + /// + /// 释放当前实例及其资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + /// + /// 一对多映射关系的排序字典。每个外部键映射到一个内部排序字典,该内部排序字典将排序键映射到相应的值。 + /// + /// 外部字典中的键类型。 + /// 内部字典中的排序键类型。 + /// 内部字典中的值类型。 + public class + OneToManySortedDictionary : Dictionary> + where TSortedKey : notnull where TKey : notnull + { + /// 缓存队列的回收限制 + private readonly int _recyclingLimit = 120; + /// 缓存队列,用于存储已回收的内部排序字典 + private readonly Queue> _queue = new Queue>(); + + /// + /// 创建一个新的 实例。 + /// + protected OneToManySortedDictionary() { } + + /// + /// 创建一个新的 实例。设置最大缓存数量 + /// + /// + /// 1:防止数据量过大、所以超过recyclingLimit的数据还是走GC. + /// 2:设置成0不控制数量,全部缓存 + /// + public OneToManySortedDictionary(int recyclingLimit) + { + _recyclingLimit = recyclingLimit; + } + + /// + /// 检查字典是否包含指定的外部键。 + /// + /// 要检查的外部键。 + /// 如果字典包含指定的外部键,则为 true;否则为 false。 + public bool Contains(TKey key) + { + return this.ContainsKey(key); + } + + /// + /// 检查字典是否包含指定的外部键和排序键。 + /// + /// 要检查的外部键。 + /// 要检查的排序键。 + /// 如果字典包含指定的外部键和排序键,则为 true;否则为 false。 + public bool Contains(TKey key, TSortedKey sortedKey) + { + return TryGetValue(key, out var dic) && dic.ContainsKey(sortedKey); + } + + /// + /// 尝试从字典中获取指定外部键对应的内部排序字典。 + /// + /// 要获取内部排序字典的外部键。 + /// 获取到的内部排序字典,如果找不到则为 null。 + /// 如果找到内部排序字典,则为 true;否则为 false。 + public new bool TryGetValue(TKey key, out SortedDictionary dic) + { + return base.TryGetValue(key, out dic); + } + + /// + /// 尝试从字典中获取指定外部键和排序键对应的值。 + /// + /// 要获取值的外部键。 + /// 要获取值的排序键。 + /// 获取到的值,如果找不到则为 default。 + /// 如果找到值,则为 true;否则为 false。 + public bool TryGetValueBySortedKey(TKey key, TSortedKey sortedKey, out TValue value) + { + if (base.TryGetValue(key, out var dic)) + { + return dic.TryGetValue(sortedKey, out value); + } + + value = default; + return false; + } + + /// + /// 向字典中添加一个值,关联到指定的外部键和排序键。 + /// + /// 要关联值的外部键。 + /// 要关联值的排序键。 + /// 要添加的值。 + public void Add(TKey key, TSortedKey sortedKey, TValue value) + { + if (!TryGetValue(key, out var dic)) + { + dic = Fetch(); + dic.Add(sortedKey, value); + Add(key, dic); + + return; + } + + dic.Add(sortedKey, value); + } + + /// + /// 从字典中移除指定外部键和排序键关联的值。 + /// + /// 要移除值的外部键。 + /// 要移除值的排序键。 + /// 如果成功移除值,则为 true;否则为 false。 + public bool RemoveSortedKey(TKey key, TSortedKey sortedKey) + { + if (!TryGetValue(key, out var dic)) + { + return false; + } + + var isRemove = dic.Remove(sortedKey); + + if (dic.Count == 0) + { + isRemove = RemoveKey(key); + } + + return isRemove; + } + + /// + /// 从字典中移除指定外部键及其关联的所有值。 + /// + /// 要移除的外部键。 + /// 如果成功移除外部键及其关联的所有值,则为 true;否则为 false。 + public bool RemoveKey(TKey key) + { + if (!TryGetValue(key, out var list)) + { + return false; + } + + Remove(key); + Recycle(list); + return true; + } + + /// + /// 从缓存队列中获取一个内部排序字典。 + /// + /// 一个内部排序字典。 + private SortedDictionary Fetch() + { + return _queue.Count <= 0 ? new SortedDictionary() : _queue.Dequeue(); + } + + /// + /// 回收一个内部排序字典到缓存队列。 + /// + /// 要回收的内部排序字典。 + private void Recycle(SortedDictionary dic) + { + dic.Clear(); + + if (_recyclingLimit != 0 && _queue.Count > _recyclingLimit) + { + return; + } + + _queue.Enqueue(dic); + } + + /// + /// 清空字典以及内部排序字典缓存队列,释放所有资源。 + /// + protected new void Clear() + { + base.Clear(); + _queue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta new file mode 100644 index 00000000..12b4b35c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/OneToManySortedDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ece24c9ac70d549ea953523c0e5f7337 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/ReuseDictionary.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/ReuseDictionary.cs new file mode 100644 index 00000000..ebe12e95 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/ReuseDictionary.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个可以重用的字典类,支持使用对象池管理。 + /// + /// 字典中键的类型。 + /// 字典中值的类型。 + public sealed class ReuseDictionary : Dictionary, IDisposable, IPool where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static ReuseDictionary Create() + { +#if FANTASY_WEBGL + var entityDictionary = Pool>.Rent(); +#else + var entityDictionary = MultiThreadPool.Rent>(); +#endif + entityDictionary._isDispose = false; + entityDictionary._isPool = true; + return entityDictionary; + } + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta new file mode 100644 index 00000000..974258da --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/ReuseDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 882f28b6907a3465dbf9df04603f74b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs new file mode 100644 index 00000000..8db66a88 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using Fantasy.Pool; + +namespace Fantasy.DataStructure.Dictionary +{ + /// + /// 提供一个可以使用对象池管理的排序字典类。 + /// + /// + /// + public sealed class SortedDictionaryPool : SortedDictionary, IDisposable, IPool where TM : notnull + { + private bool _isPool; + private bool _isDispose; + + /// + /// 释放实例占用的资源。 + /// + public void Dispose() + { + if (_isDispose) + { + return; + } + + _isDispose = true; + Clear(); +#if FANTASY_WEBGL + Pool>.Return(this); +#else + MultiThreadPool.Return(this); +#endif + } + + /// + /// 创建一个新的 实例。 + /// + /// 新创建的实例。 + public static SortedDictionaryPool Create() + { +#if FANTASY_WEBGL + var dictionary = Pool>.Rent(); +#else + var dictionary = MultiThreadPool.Rent>(); +#endif + dictionary._isDispose = false; + dictionary._isPool = true; + return dictionary; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta new file mode 100644 index 00000000..a194859e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/Dictionary/SortedDictionaryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 060121583adb64f03973db7e623b91de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections.meta new file mode 100644 index 00000000..fa09ab36 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6e0c05d3a90bc4c5d88144a87507f06d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/LICENSE b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/LICENSE new file mode 100644 index 00000000..2ca22487 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Nevin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/LICENSE.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/LICENSE.meta new file mode 100644 index 00000000..6dcaebd9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7e1846e320c8146de9a12ee013d7f387 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections.meta new file mode 100644 index 00000000..4a1da861 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7c8784e99a0cb4cea8ad217cf8c094b1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/BitOperationsHelpers.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/BitOperationsHelpers.cs new file mode 100644 index 00000000..3b889294 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/BitOperationsHelpers.cs @@ -0,0 +1,325 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET7_0_OR_GREATER +using System.Numerics; +using System.Runtime.Intrinsics; +#else +using System; +#endif + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// BitOperations helpers + /// + internal static class BitOperationsHelpers + { +#if !NET7_0_OR_GREATER + /// + /// DeBruijn sequence + /// + private static ReadOnlySpan Log2DeBruijn => new byte[32] + { + 0, 9, 1, 10, 13, 21, 2, 29, + 11, 14, 16, 18, 22, 25, 3, 30, + 8, 12, 20, 28, 15, 17, 24, 7, + 19, 27, 23, 6, 26, 5, 4, 31 + }; +#endif + + /// + /// Log2 + /// + /// Value + /// Log2 + public static int Log2(int value) => Log2((uint)value); + + /// + /// Log2 + /// + /// Value + /// Log2 + public static int Log2(uint value) + { +#if NET7_0_OR_GREATER + return BitOperations.Log2(value); +#else + value |= 1; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(int)((value * 130329821U) >> 27)); +#endif + } + + /// + /// And + /// + /// Destination + /// Source + /// Count + public static void And(Span destination, Span source, uint count) + { + switch (count) + { + case 7: + destination[6] &= source[6]; + goto case 6; + case 6: + destination[5] &= source[5]; + goto case 5; + case 5: + destination[4] &= source[4]; + goto case 4; + case 4: + destination[3] &= source[3]; + goto case 3; + case 3: + destination[2] &= source[2]; + goto case 2; + case 2: + destination[1] &= source[1]; + goto case 1; + case 1: + destination[0] &= source[0]; + return; + case 0: + return; + } + + ref var left = ref MemoryMarshal.GetReference(destination); + ref var right = ref MemoryMarshal.GetReference(source); +#if NET7_0_OR_GREATER + uint i = 0; + if (Vector256.IsHardwareAccelerated) + { + var n = count - 7; + for (; i < n; i += 8) + { + var result = Vector256.LoadUnsafe(ref left, i) & Vector256.LoadUnsafe(ref right, i); + result.StoreUnsafe(ref left, i); + } + } + else if (Vector128.IsHardwareAccelerated) + { + var n = count - 3; + for (; i < n; i += 4) + { + var result = Vector128.LoadUnsafe(ref left, i) & Vector128.LoadUnsafe(ref right, i); + result.StoreUnsafe(ref left, i); + } + } + + for (; i < count; ++i) + Unsafe.Add(ref left, i) &= Unsafe.Add(ref right, i); +#else + var i = 0; + for (; i < count; ++i) + Unsafe.Add(ref left, i) &= Unsafe.Add(ref right, i); +#endif + } + + /// + /// Or + /// + /// Destination + /// Source + /// Count + public static void Or(Span destination, Span source, uint count) + { + switch (count) + { + case 7: + destination[6] |= source[6]; + goto case 6; + case 6: + destination[5] |= source[5]; + goto case 5; + case 5: + destination[4] |= source[4]; + goto case 4; + case 4: + destination[3] |= source[3]; + goto case 3; + case 3: + destination[2] |= source[2]; + goto case 2; + case 2: + destination[1] |= source[1]; + goto case 1; + case 1: + destination[0] |= source[0]; + return; + case 0: + return; + } + + ref var left = ref MemoryMarshal.GetReference(destination); + ref var right = ref MemoryMarshal.GetReference(source); +#if NET7_0_OR_GREATER + uint i = 0; + if (Vector256.IsHardwareAccelerated) + { + var n = count - 7; + for (; i < n; i += 8) + { + var result = Vector256.LoadUnsafe(ref left, i) | Vector256.LoadUnsafe(ref right, i); + result.StoreUnsafe(ref left, i); + } + } + else if (Vector128.IsHardwareAccelerated) + { + var n = count - 3; + for (; i < n; i += 4) + { + var result = Vector128.LoadUnsafe(ref left, i) | Vector128.LoadUnsafe(ref right, i); + result.StoreUnsafe(ref left, i); + } + } + + for (; i < count; ++i) + Unsafe.Add(ref left, i) |= Unsafe.Add(ref right, i); +#else + var i = 0; + for (; i < count; ++i) + Unsafe.Add(ref left, i) |= Unsafe.Add(ref right, i); +#endif + } + + /// + /// Xor + /// + /// Destination + /// Source + /// Count + public static void Xor(Span destination, Span source, uint count) + { + switch (count) + { + case 7: + destination[6] ^= source[6]; + goto case 6; + case 6: + destination[5] ^= source[5]; + goto case 5; + case 5: + destination[4] ^= source[4]; + goto case 4; + case 4: + destination[3] ^= source[3]; + goto case 3; + case 3: + destination[2] ^= source[2]; + goto case 2; + case 2: + destination[1] ^= source[1]; + goto case 1; + case 1: + destination[0] ^= source[0]; + return; + case 0: + return; + } + + ref var left = ref MemoryMarshal.GetReference(destination); + ref var right = ref MemoryMarshal.GetReference(source); +#if NET7_0_OR_GREATER + uint i = 0; + if (Vector256.IsHardwareAccelerated) + { + var n = count - 7; + for (; i < n; i += 8) + { + var result = Vector256.LoadUnsafe(ref left, i) ^ Vector256.LoadUnsafe(ref right, i); + result.StoreUnsafe(ref left, i); + } + } + else if (Vector128.IsHardwareAccelerated) + { + var n = count - 3; + for (; i < n; i += 4) + { + var result = Vector128.LoadUnsafe(ref left, i) ^ Vector128.LoadUnsafe(ref right, i); + result.StoreUnsafe(ref left, i); + } + } + + for (; i < count; ++i) + Unsafe.Add(ref left, i) ^= Unsafe.Add(ref right, i); +#else + var i = 0; + for (; i < count; ++i) + Unsafe.Add(ref left, i) ^= Unsafe.Add(ref right, i); +#endif + } + + /// + /// Not + /// + /// Destination + /// Count + public static void Not(Span destination, uint count) + { + switch (count) + { + case 7: + destination[6] = ~destination[6]; + goto case 6; + case 6: + destination[5] = ~destination[5]; + goto case 5; + case 5: + destination[4] = ~destination[4]; + goto case 4; + case 4: + destination[3] = ~destination[3]; + goto case 3; + case 3: + destination[2] = ~destination[2]; + goto case 2; + case 2: + destination[1] = ~destination[1]; + goto case 1; + case 1: + destination[0] = ~destination[0]; + return; + case 0: + return; + } + + ref var value = ref MemoryMarshal.GetReference(destination); +#if NET7_0_OR_GREATER + uint i = 0; + if (Vector256.IsHardwareAccelerated) + { + var n = count - 7; + for (; i < n; i += 8) + { + var result = ~Vector256.LoadUnsafe(ref value, i); + result.StoreUnsafe(ref value, i); + } + } + else if (Vector128.IsHardwareAccelerated) + { + var n = count - 3; + for (; i < n; i += 4) + { + var result = ~Vector128.LoadUnsafe(ref value, i); + result.StoreUnsafe(ref value, i); + } + } + + for (; i < count; ++i) + Unsafe.Add(ref value, i) = ~ Unsafe.Add(ref value, i); +#else + var i = 0; + for (; i < count; ++i) + Unsafe.Add(ref value, i) = ~ Unsafe.Add(ref value, i); +#endif + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/BitOperationsHelpers.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/BitOperationsHelpers.cs.meta new file mode 100644 index 00000000..56803781 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/BitOperationsHelpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a92934f7689f140088cf35008fc577a9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/HashHelpers.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/HashHelpers.cs new file mode 100644 index 00000000..fedc5108 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/HashHelpers.cs @@ -0,0 +1,125 @@ +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Hash helpers + /// + internal static class HashHelpers + { + /// + /// Primes + /// + private static ReadOnlySpan Primes => new int[72] + { + 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, + 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, + 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, + 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, + 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 + }; + + /// + /// Binary search + /// + /// Min + /// Prime + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int BinarySearch(int min) + { + var left = 0; + var right = 71; + ref var value = ref MemoryMarshal.GetReference(Primes); + while (left <= right) + { + var mid = left + (right - left) / 2; + if (Unsafe.Add(ref value, mid) >= min) + right = mid - 1; + else + left = mid + 1; + } + + return Unsafe.Add(ref value, left); + } + + /// + /// Is prime + /// + /// Candidate + /// Is prime + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsPrime(int candidate) + { + if ((candidate & 1) != 0) + { + var limit = (int)Math.Sqrt(candidate); + for (var divisor = 3; divisor <= limit; divisor += 2) + { + if (candidate % divisor == 0) + return false; + } + + return true; + } + + return candidate == 2; + } + + /// + /// Get prime + /// + /// Min + /// Prime + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetPrime(int min) + { + if (min < 0) + throw new ArgumentException("HTCapacityOverflow"); + if (min <= 7199369) + return BinarySearch(min); + for (var i = min | 1; i < int.MaxValue; i += 2) + { + if (IsPrime(i) && (i - 1) % 101 != 0) + return i; + } + + return min; + } + + /// + /// Expand prime + /// + /// Old size + /// Prime + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ExpandPrime(int oldSize) + { + var newSize = 2 * oldSize; + return (uint)newSize > 2147483587 && 2147483587 > oldSize ? 2147483587 : GetPrime(newSize); + } + + /// + /// Get fast mod multiplier + /// + /// Divisor + /// Fast mod multiplier + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong GetFastModMultiplier(uint divisor) => ulong.MaxValue / divisor + 1; + + /// + /// Fast mod + /// + /// Value + /// Divisor + /// Multiplier + /// Mod + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint FastMod(uint value, uint divisor, ulong multiplier) => (uint)(((((multiplier * value) >> 32) + 1) * divisor) >> 32); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/HashHelpers.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/HashHelpers.cs.meta new file mode 100644 index 00000000..b50cbe29 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/HashHelpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 06d18d662209a4e2f8fecbe95ed58edf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArray.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArray.cs new file mode 100644 index 00000000..e8c372eb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArray.cs @@ -0,0 +1,297 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native array + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeArray : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Array + /// + private readonly T* _array; + + /// + /// Length + /// + private readonly int _length; + + /// + /// Structure + /// + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArray(int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _array = (T*)NativeMemoryAllocator.Alloc((uint)(length * sizeof(T))); + _length = length; + } + + /// + /// Structure + /// + /// Length + /// Zeroed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArray(int length, bool zeroed) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _array = zeroed ? (T*)NativeMemoryAllocator.AllocZeroed((uint)(length * sizeof(T))) : (T*)NativeMemoryAllocator.Alloc((uint)(length * sizeof(T))); + _length = length; + } + + /// + /// Structure + /// + /// Array + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArray(T* array, int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _array = array; + _length = length; + } + + /// + /// Is created + /// + public bool IsCreated => _array != null; + + /// + /// Is empty + /// + public bool IsEmpty => _length == 0; + + /// + /// Get reference + /// + /// Index + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _array[index]; + } + + /// + /// Get reference + /// + /// Index + public ref T this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _array[index]; + } + + /// + /// Array + /// + public T* Array => _array; + + /// + /// Length + /// + public int Length => _length; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeArray other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeArray nativeArray && nativeArray == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_array; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeArray<{typeof(T).Name}>[{_length}]"; + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Span(NativeArray nativeArray) => nativeArray.AsSpan(); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(NativeArray nativeArray) => nativeArray.AsReadOnlySpan(); + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeArray left, NativeArray right) => left._length == right._length && left._array == right._array; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeArray left, NativeArray right) => left._length != right._length || left._array != right._array; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_array == null) + return; + NativeMemoryAllocator.Free(_array); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => Unsafe.InitBlockUnaligned(_array, 0, (uint)(_length * sizeof(T))); + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() => MemoryMarshal.CreateSpan(ref *_array, _length); + + /// + /// As span + /// + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int length) => MemoryMarshal.CreateSpan(ref *_array, length); + + /// + /// As span + /// + /// Start + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int start, int length) => MemoryMarshal.CreateSpan(ref *(_array + start), length); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan() => MemoryMarshal.CreateReadOnlySpan(ref *_array, _length); + + /// + /// As readOnly span + /// + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int length) => MemoryMarshal.CreateReadOnlySpan(ref *_array, length); + + /// + /// As readOnly span + /// + /// Start + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int start, int length) => MemoryMarshal.CreateReadOnlySpan(ref *(_array + start), length); + + /// + /// Empty + /// + public static NativeArray Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public ref struct Enumerator + { + /// + /// NativeArray + /// + private readonly NativeArray _nativeArray; + + /// + /// Index + /// + private int _index; + + /// + /// Structure + /// + /// NativeArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeArray nativeArray) + { + _nativeArray = nativeArray; + _index = -1; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + var index = _index + 1; + if (index < _nativeArray._length) + { + _index = index; + return true; + } + + return false; + } + + /// + /// Current + /// + public ref T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _nativeArray[_index]; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArray.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArray.cs.meta new file mode 100644 index 00000000..b5e3b89c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArray.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 44a472b0265094fccbc88f3691985d78 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayPool.cs new file mode 100644 index 00000000..b31e428b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayPool.cs @@ -0,0 +1,372 @@ +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET5_0_OR_GREATER +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// NativeMemoryPool + /// + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeArrayPool : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Buckets + /// + private readonly NativeArrayPoolBucket* _buckets; + + /// + /// Length + /// + private readonly int _length; + + /// + /// Size + /// + private readonly int _size; + + /// + /// Structure + /// + /// Size + /// Max length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArrayPool(int size, int maxLength) + { + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size), size, "MustBePositive"); + if (maxLength < 0) + throw new ArgumentOutOfRangeException(nameof(maxLength), maxLength, "MustBeNonNegative"); + if (maxLength > 1073741824) + maxLength = 1073741824; + else if (maxLength < 16) + maxLength = 16; + var length = SelectBucketIndex(maxLength) + 1; + var buckets = (NativeArrayPoolBucket*)NativeMemoryAllocator.Alloc((uint)(length * sizeof(NativeArrayPoolBucket))); + for (var i = 0; i < length; ++i) + buckets[i].Initialize(size, 16 << i); + _buckets = buckets; + _length = length; + _size = size; + } + + /// + /// Is created + /// + public bool IsCreated => _buckets != null; + + /// + /// Size + /// + public int Size => _size; + + /// + /// Max length + /// + public int MaxLength => 16 << (_length - 1); + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeArrayPool other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeArrayPool nativeArrayPool && nativeArrayPool == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_buckets; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeArrayPool<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeArrayPool left, NativeArrayPool right) => left._buckets == right._buckets; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeArrayPool left, NativeArrayPool right) => left._buckets != right._buckets; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_buckets == null) + return; + for (var i = 0; i < _length; ++i) + _buckets[i].Dispose(); + NativeMemoryAllocator.Free(_buckets); + } + + /// + /// Rent buffer + /// + /// Minimum buffer length + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArray Rent(int minimumLength) + { + if (minimumLength < 0) + throw new ArgumentOutOfRangeException(nameof(minimumLength), minimumLength, "MustBeNonNegative"); + var index = SelectBucketIndex(minimumLength); + if (index < _length) + return _buckets[index].Rent(); + throw new ArgumentOutOfRangeException(nameof(minimumLength), minimumLength, "BiggerThanCollection"); + } + + /// + /// Rent buffer + /// + /// Minimum buffer length + /// Buffer + /// Rented + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryRent(int minimumLength, out NativeArray array) + { + if (minimumLength < 0) + { + array = default; + return false; + } + + var index = SelectBucketIndex(minimumLength); + if (index < _length) + { + array = _buckets[index].Rent(); + return true; + } + + array = default; + return false; + } + + /// + /// Return buffer + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(in NativeArray array) + { + var length = array.Length; + if (length < 16 || (length & (length - 1)) != 0) + throw new ArgumentException("BufferNotFromPool", nameof(array)); + var bucket = SelectBucketIndex(length); + if (bucket >= _length) + throw new ArgumentException("BufferNotFromPool", nameof(array)); + _buckets[bucket].Return(array.Array); + } + + /// + /// Try return buffer + /// + /// Buffer + /// Returned + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryReturn(in NativeArray array) + { + var length = array.Length; + if (length < 16 || (length & (length - 1)) != 0) + return false; + var bucket = SelectBucketIndex(length); + if (bucket >= _length) + return false; + _buckets[bucket].Return(array.Array); + return true; + } + + /// + /// Return buffer + /// + /// Length + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(int length, T* array) + { + if (length < 16 || (length & (length - 1)) != 0) + throw new ArgumentException("BufferNotFromPool", nameof(array)); + var bucket = SelectBucketIndex(length); + if (bucket >= _length) + throw new ArgumentException("BufferNotFromPool", nameof(array)); + _buckets[bucket].Return(array); + } + + /// + /// Try return buffer + /// + /// Length + /// Buffer + /// Returned + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryReturn(int length, T* array) + { + if (length < 16 || (length & (length - 1)) != 0) + return false; + var bucket = SelectBucketIndex(length); + if (bucket >= _length) + return false; + _buckets[bucket].Return(array); + return true; + } + + /// + /// Select bucket index + /// + /// Buffer size + /// Bucket index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int SelectBucketIndex(int bufferSize) => BitOperationsHelpers.Log2(((uint)bufferSize - 1) | 15) - 3; + + /// + /// Empty + /// + public static NativeArrayPool Empty => new(); + + /// + /// NativeArrayPool bucket + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeArrayPoolBucket : IDisposable + { + /// + /// Size + /// + private int _size; + + /// + /// Length + /// + private int _length; + + /// + /// Buffers + /// + private T** _array; + + /// + /// Index + /// + private int _index; + + /// + /// Memory pool + /// + private NativeMemoryPool _memoryPool; + + /// + /// State lock + /// + private SpinLock _lock; + + /// + /// Structure + /// + /// Size + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(int size, int length) + { + _size = size; + _length = length; + _array = (T**)NativeMemoryAllocator.AllocZeroed((uint)(size * sizeof(T*))); + _index = 0; + _memoryPool = new NativeMemoryPool(size, length * sizeof(T), 0); + _lock = new SpinLock(); + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + NativeMemoryAllocator.Free(_array); + _memoryPool.Dispose(); + } + + /// + /// Rent buffer + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArray Rent() + { + T* ptr = null; + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + if (_index < _size) + { + ptr = _array[_index]; + _array[_index++] = null; + } + + if (ptr == null) + ptr = (T*)_memoryPool.Rent(); + } + finally + { + if (lockTaken) + _lock.Exit(false); + } + + return new NativeArray(ptr, _length); + } + + /// + /// Return buffer + /// + /// Pointer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(T* ptr) + { + var lockTaken = false; + try + { + _lock.Enter(ref lockTaken); + if (_index != 0) + _array[--_index] = ptr; + else + _memoryPool.Return(ptr); + } + finally + { + if (lockTaken) + _lock.Exit(false); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayPool.cs.meta new file mode 100644 index 00000000..e126f159 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e0181fd493dbd46abb66ae1d7619eaae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayReference.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayReference.cs new file mode 100644 index 00000000..62a62da9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayReference.cs @@ -0,0 +1,248 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8600 +#pragma warning disable CS8603 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native array reference + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public struct NativeArrayReference : IDisposable, IEquatable> + { + /// + /// Handle + /// + private GCHandle _handle; + + /// + /// Length + /// + private readonly int _length; + + /// + /// Structure + /// + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArrayReference(int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = GCHandle.Alloc(new T[length], GCHandleType.Normal); + _length = length; + } + + /// + /// Structure + /// + /// Length + /// GCHandle type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArrayReference(int length, GCHandleType type) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = GCHandle.Alloc(new T[length], type); + _length = length; + } + + /// + /// Structure + /// + /// Array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArrayReference(T[] array) + { + if (array == null) + throw new ArgumentNullException(nameof(array), "MustBeNotNull"); + _handle = GCHandle.Alloc(array, GCHandleType.Normal); + _length = array.Length; + } + + /// + /// Structure + /// + /// Array + /// GCHandle type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArrayReference(T[] array, GCHandleType type) + { + if (array == null) + throw new ArgumentNullException(nameof(array), "MustBeNotNull"); + _handle = GCHandle.Alloc(array, type); + _length = array.Length; + } + + /// + /// Is created + /// + public bool IsCreated => _handle.IsAllocated; + + /// + /// Is empty + /// + public bool IsEmpty => _length == 0; + + /// + /// Get reference + /// + /// Index + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref Array[index]; + } + + /// + /// Get reference + /// + /// Index + public ref T this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref Array[index]; + } + + /// + /// Array + /// + public T[] Array + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (T[])_handle.Target; + } + + /// + /// Length + /// + public int Length => _length; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeArrayReference other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeArrayReference nativeArrayReference && nativeArrayReference == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeArrayReference<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeArrayReference left, NativeArrayReference right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeArrayReference left, NativeArrayReference right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (!_handle.IsAllocated) + return; + _handle.Free(); + } + + /// + /// Empty + /// + public static NativeArrayReference Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(Array); + + /// + /// Enumerator + /// + public ref struct Enumerator + { + /// + /// Array + /// + private readonly T[] _array; + + /// + /// Index + /// + private int _index; + + /// + /// Structure + /// + /// Array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(T[] array) + { + _array = array; + _index = -1; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + var index = _index + 1; + if (index < _array.Length) + { + _index = index; + return true; + } + + return false; + } + + /// + /// Current + /// + public ref T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _array[_index]; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayReference.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayReference.cs.meta new file mode 100644 index 00000000..bfc55008 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArrayReference.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d9f0b1359e8a5465cbc412dccdb1fb8d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArraySegment.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArraySegment.cs new file mode 100644 index 00000000..aeac3dfb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArraySegment.cs @@ -0,0 +1,386 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native array segment + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeArraySegment : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Array + /// + private readonly T* _array; + + /// + /// Offset + /// + private readonly int _offset; + + /// + /// Count + /// + private readonly int _count; + + /// + /// Structure + /// + /// Array + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment(T* array, int count) + { + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "MustBeNonNegative"); + _array = array; + _offset = 0; + _count = count; + } + + /// + /// Structure + /// + /// Array + /// Offset + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment(T* array, int offset, int count) + { + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset), offset, "MustBeNonNegative"); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "MustBeNonNegative"); + _array = array; + _offset = offset; + _count = count; + } + + /// + /// Structure + /// + /// Array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment(NativeArray array) + { + _array = array.Array; + _offset = 0; + _count = array.Length; + } + + /// + /// Structure + /// + /// Array + /// Offset + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment(NativeArray array, int offset, int count) + { + _array = array.Array; + _offset = offset; + _count = count; + } + + /// + /// Structure + /// + /// Array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment(NativeMemoryArray array) + { + _array = array.Array; + _offset = 0; + _count = array.Length; + } + + /// + /// Structure + /// + /// Array + /// Offset + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment(NativeMemoryArray array, int offset, int count) + { + _array = array.Array; + _offset = offset; + _count = count; + } + + /// + /// Is created + /// + public bool IsCreated => _array != null; + + /// + /// Is empty + /// + public bool IsEmpty => _count == 0; + + /// + /// Get reference + /// + /// Index + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _array[_offset + index]; + } + + /// + /// Get reference + /// + /// Index + public ref T this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _array[_offset + index]; + } + + /// + /// Array + /// + public T* Array => _array; + + /// + /// Offset + /// + public int Offset => _offset; + + /// + /// Count + /// + public int Count => _count; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeArraySegment other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeArraySegment nativeArraySegment && nativeArraySegment == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_array; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeArraySegment<{typeof(T).Name}>[{_offset}, {_count}]"; + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Span(NativeArraySegment nativeArraySegment) => nativeArraySegment.AsSpan(); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(NativeArraySegment nativeArraySegment) => nativeArraySegment.AsReadOnlySpan(); + + /// + /// As native array + /// + /// Native array segment + /// NativeArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeArray(NativeArraySegment nativeArraySegment) => new(nativeArraySegment._array, nativeArraySegment._offset + nativeArraySegment._count); + + /// + /// As native array segment + /// + /// Native array + /// NativeArraySegment + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeArraySegment(NativeArray nativeArray) => new(nativeArray); + + /// + /// As native array segment + /// + /// Native array + /// NativeArraySegment + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeArraySegment(NativeMemoryArray nativeArray) => new(nativeArray); + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeArraySegment left, NativeArraySegment right) => left._offset == right._offset && left._count == right._count && left._array == right._array; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeArraySegment left, NativeArraySegment right) => left._offset != right._offset || left._count != right._count || left._array != right._array; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_array == null) + return; + NativeMemoryAllocator.Free(_array); + } + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() => MemoryMarshal.CreateSpan(ref *(_array + _offset), _count); + + /// + /// As span + /// + /// Count + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int count) => MemoryMarshal.CreateSpan(ref *(_array + _offset), count); + + /// + /// As span + /// + /// Start + /// Count + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int start, int count) => MemoryMarshal.CreateSpan(ref *(_array + _offset + start), count); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan() => MemoryMarshal.CreateReadOnlySpan(ref *(_array + _offset), _count); + + /// + /// As readOnly span + /// + /// Count + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int count) => MemoryMarshal.CreateReadOnlySpan(ref *(_array + _offset), count); + + /// + /// As readOnly span + /// + /// Start + /// Count + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int start, int count) => MemoryMarshal.CreateReadOnlySpan(ref *(_array + _offset + start), count); + + /// + /// Slice + /// + /// Start + /// NativeArraySegment + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment Slice(int start) => new(_array, _offset + start, _count - start); + + /// + /// Slice + /// + /// Start + /// Count + /// NativeArraySegment + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeArraySegment Slice(int start, int count) => new(_array, _offset + start, count); + + /// + /// Empty + /// + public static NativeArraySegment Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public ref struct Enumerator + { + /// + /// NativeArraySegment + /// + private readonly NativeArraySegment _nativeArraySegment; + + /// + /// Index + /// + private int _index; + + /// + /// Structure + /// + /// NativeArraySegment + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeArraySegment nativeArraySegment) + { + _nativeArraySegment = nativeArraySegment; + _index = -1; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + var index = _index + 1; + if (index < _nativeArraySegment._count) + { + _index = index; + return true; + } + + return false; + } + + /// + /// Current + /// + public ref T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _nativeArraySegment[_index]; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArraySegment.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArraySegment.cs.meta new file mode 100644 index 00000000..74301772 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeArraySegment.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3865e132548ee4d8481ddd5a49107ec3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBitArray.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBitArray.cs new file mode 100644 index 00000000..aa192e77 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBitArray.cs @@ -0,0 +1,590 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native bit array + /// + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeBitArray : IDisposable, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeBitArrayHandle + { + /// + /// Array + /// + public NativeArray Array; + + /// + /// Length + /// + public int Length; + } + + /// + /// Handle + /// + private readonly NativeBitArrayHandle* _handle; + + /// + /// Structure + /// + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray(int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = (NativeBitArrayHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeBitArrayHandle)); + _handle->Array = new NativeArray(GetInt32ArrayLengthFromBitLength(length)); + _handle->Length = length; + } + + /// + /// Structure + /// + /// Length + /// Default value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray(int length, bool defaultValue) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = (NativeBitArrayHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeBitArrayHandle)); + _handle->Array = new NativeArray(GetInt32ArrayLengthFromBitLength(length)); + _handle->Length = length; + if (defaultValue) + { + _handle->Array.AsSpan().Fill(-1); + Div32Rem(length, out var extraBits); + if (extraBits > 0) + _handle->Array[^1] = (1 << extraBits) - 1; + } + else + { + _handle->Array.Clear(); + } + } + + /// + /// Structure + /// + /// Array + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray(int* array, int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = (NativeBitArrayHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeBitArrayHandle)); + _handle->Array = new NativeArray(array, GetInt32ArrayLengthFromBitLength(length)); + _handle->Length = length; + } + + /// + /// Structure + /// + /// Array + /// Length + /// Default value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray(int* array, int length, bool defaultValue) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = (NativeBitArrayHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeBitArrayHandle)); + _handle->Array = new NativeArray(array, GetInt32ArrayLengthFromBitLength(length)); + _handle->Length = length; + if (defaultValue) + { + _handle->Array.AsSpan().Fill(-1); + Div32Rem(length, out var extraBits); + if (extraBits > 0) + _handle->Array[^1] = (1 << extraBits) - 1; + } + else + { + _handle->Array.Clear(); + } + } + + /// + /// Structure + /// + /// Array + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray(NativeArray array, int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + var intCount = GetInt32ArrayLengthFromBitLength(length); + if (array.Length < intCount) + throw new ArgumentOutOfRangeException(nameof(array), array.Length, $"Requires size is {intCount}, but buffer length is {array.Length}."); + _handle = (NativeBitArrayHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeBitArrayHandle)); + _handle->Array = array; + _handle->Length = length; + } + + /// + /// Structure + /// + /// Array + /// Length + /// Default value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray(NativeArray array, int length, bool defaultValue) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + var intCount = GetInt32ArrayLengthFromBitLength(length); + if (array.Length < intCount) + throw new ArgumentOutOfRangeException(nameof(array), array.Length, $"Requires size is {intCount}, but buffer length is {array.Length}."); + _handle = (NativeBitArrayHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeBitArrayHandle)); + _handle->Array = array; + _handle->Length = length; + if (defaultValue) + { + _handle->Array.AsSpan().Fill(-1); + Div32Rem(length, out var extraBits); + if (extraBits > 0) + _handle->Array[^1] = (1 << extraBits) - 1; + } + else + { + _handle->Array.Clear(); + } + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Array + /// + public NativeArray Array => _handle->Array; + + /// + /// Length + /// + public int Length + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _handle->Length; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(value), value, "MustBeNonNegative"); + var newLength = GetInt32ArrayLengthFromBitLength(value); + if (newLength > _handle->Array.Length || newLength + 256 < _handle->Array.Length) + { + var array = new NativeArray(newLength); + Unsafe.CopyBlockUnaligned(array.Array, _handle->Array.Array, (uint)(_handle->Array.Length * sizeof(int))); + Unsafe.InitBlockUnaligned(array.Array + _handle->Array.Length, 0, (uint)(newLength - _handle->Array.Length)); + _handle->Array.Dispose(); + _handle->Array = array; + } + + if (value > _handle->Length) + { + var last = (_handle->Length - 1) >> 5; + Div32Rem(_handle->Length, out var bits); + if (bits > 0) + _handle->Array[last] &= (1 << bits) - 1; + _handle->Array.AsSpan(last + 1, newLength - last - 1).Clear(); + } + + _handle->Length = value; + } + } + + /// + /// Get or set value + /// + /// Index + public bool this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Get(index); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Set(index, value); + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeBitArray other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeBitArray nativeBitArray && nativeBitArray == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => "NativeBitArray"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeBitArray left, NativeBitArray right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeBitArray left, NativeBitArray right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + _handle->Array.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Get + /// + /// Index + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Get(int index) + { + if ((uint)index >= (uint)_handle->Length) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLess"); + return (_handle->Array[index >> 5] & (1 << index)) != 0; + } + + /// + /// + /// Index + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Set(int index, bool value) + { + if ((uint)index >= (uint)_handle->Length) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLess"); + var bitMask = 1 << index; + ref var segment = ref _handle->Array[index >> 5]; + if (value) + segment |= bitMask; + else + segment &= ~bitMask; + } + + /// + /// Set all + /// + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetAll(bool value) + { + var arrayLength = GetInt32ArrayLengthFromBitLength(Length); + var span = _handle->Array.AsSpan(0, arrayLength); + if (value) + { + span.Fill(-1); + Div32Rem(_handle->Length, out var extraBits); + if (extraBits > 0) + span[^1] &= (1 << extraBits) - 1; + } + else + { + span.Clear(); + } + } + + /// + /// And + /// + /// Value + /// NativeBitArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray And(NativeBitArray value) + { + if (!value.IsCreated) + throw new ArgumentNullException(nameof(value)); + var count = GetInt32ArrayLengthFromBitLength(Length); + if (Length != value.Length || (uint)count > (uint)_handle->Array.Length || (uint)count > (uint)value._handle->Array.Length) + throw new ArgumentException("ArrayLengthsDiffer"); + BitOperationsHelpers.And(_handle->Array, value._handle->Array, (uint)count); + return this; + } + + /// + /// Or + /// + /// Value + /// NativeBitArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray Or(NativeBitArray value) + { + if (!value.IsCreated) + throw new ArgumentNullException(nameof(value)); + var count = GetInt32ArrayLengthFromBitLength(Length); + if (Length != value.Length || (uint)count > (uint)_handle->Array.Length || (uint)count > (uint)value._handle->Array.Length) + throw new ArgumentException("ArrayLengthsDiffer"); + BitOperationsHelpers.Or(_handle->Array, value._handle->Array, (uint)count); + return this; + } + + /// + /// Xor + /// + /// Value + /// NativeBitArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray Xor(NativeBitArray value) + { + if (!value.IsCreated) + throw new ArgumentNullException(nameof(value)); + var count = GetInt32ArrayLengthFromBitLength(Length); + if (Length != value.Length || (uint)count > (uint)_handle->Array.Length || (uint)count > (uint)value._handle->Array.Length) + throw new ArgumentException("ArrayLengthsDiffer"); + BitOperationsHelpers.Xor(_handle->Array, value._handle->Array, (uint)count); + return this; + } + + /// + /// Not + /// + /// NativeBitArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray Not() + { + var count = GetInt32ArrayLengthFromBitLength(Length); + BitOperationsHelpers.Not(_handle->Array, (uint)count); + return this; + } + + /// + /// Right shift + /// + /// Count + /// NativeBitArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray RightShift(int count) + { + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "MustBeNonNegative"); + if (count == 0) + return this; + var toIndex = 0; + var length = GetInt32ArrayLengthFromBitLength(_handle->Length); + if (count < _handle->Length) + { + var fromIndex = Div32Rem(count, out var shiftCount); + Div32Rem(_handle->Length, out var extraBits); + if (shiftCount == 0) + { + unchecked + { + var mask = uint.MaxValue >> (32 - extraBits); + _handle->Array[length - 1] &= (int)mask; + } + + Unsafe.CopyBlockUnaligned(_handle->Array.Array, _handle->Array.Array + fromIndex, (uint)((length - fromIndex) * sizeof(int))); + toIndex = length - fromIndex; + } + else + { + var lastIndex = length - 1; + unchecked + { + while (fromIndex < lastIndex) + { + var right = (uint)_handle->Array[fromIndex] >> shiftCount; + var left = _handle->Array[++fromIndex] << (32 - shiftCount); + _handle->Array[toIndex++] = left | (int)right; + } + + var mask = uint.MaxValue >> (32 - extraBits); + mask &= (uint)_handle->Array[fromIndex]; + _handle->Array[toIndex++] = (int)(mask >> shiftCount); + } + } + } + + _handle->Array.AsSpan(toIndex, length - toIndex).Clear(); + return this; + } + + /// + /// Left shift + /// + /// Count + /// NativeBitArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBitArray LeftShift(int count) + { + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "MustBeNonNegative"); + if (count == 0) + return this; + int lengthToClear; + if (count < _handle->Length) + { + var lastIndex = (_handle->Length - 1) >> 5; + lengthToClear = Div32Rem(count, out var shiftCount); + if (shiftCount == 0) + { + Unsafe.CopyBlockUnaligned(_handle->Array.Array + lengthToClear, _handle->Array.Array, (uint)((lastIndex + 1 - lengthToClear) * sizeof(int))); + } + else + { + var fromIndex = lastIndex - lengthToClear; + unchecked + { + while (fromIndex > 0) + { + var left = _handle->Array[fromIndex] << shiftCount; + var right = (uint)_handle->Array[--fromIndex] >> (32 - shiftCount); + _handle->Array[lastIndex] = left | (int)right; + lastIndex--; + } + + _handle->Array[lastIndex] = _handle->Array[fromIndex] << shiftCount; + } + } + } + else + { + lengthToClear = GetInt32ArrayLengthFromBitLength(_handle->Length); + } + + _handle->Array.AsSpan(0, lengthToClear).Clear(); + return this; + } + + /// + /// Has all set + /// + /// All set + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool HasAllSet() + { + Div32Rem(_handle->Length, out var extraBits); + var intCount = GetInt32ArrayLengthFromBitLength(_handle->Length); + if (extraBits != 0) + intCount--; +#if NET8_0_OR_GREATER + if (_handle->Array.AsSpan(0, intCount).ContainsAnyExcept(-1)) + return false; +#elif NET7_0_OR_GREATER + if (_handle->Array.AsSpan(0, intCount).IndexOfAnyExcept(-1) >= 0) + return false; +#else + for (var i = 0; i < intCount; ++i) + { + if (_handle->Array[i] != -1) + return false; + } +#endif + if (extraBits == 0) + return true; + var mask = (1 << extraBits) - 1; + return (_handle->Array[intCount] & mask) == mask; + } + + /// + /// Has any set + /// + /// Any set + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool HasAnySet() + { + Div32Rem(_handle->Length, out var extraBits); + var intCount = GetInt32ArrayLengthFromBitLength(_handle->Length); + if (extraBits != 0) + intCount--; +#if NET8_0_OR_GREATER + if (_handle->Array.AsSpan(0, intCount).ContainsAnyExcept(0)) + return true; +#elif NET7_0_OR_GREATER + if (_handle->Array.AsSpan(0, intCount).IndexOfAnyExcept(0) >= 0) + return true; +#else + for (var i = 0; i < intCount; ++i) + { + if (_handle->Array[i] != 0) + return true; + } +#endif + if (extraBits == 0) + return false; + return (_handle->Array[intCount] & ((1 << extraBits) - 1)) != 0; + } + + /// + /// Get int32 array length from bit length + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetInt32ArrayLengthFromBitLength(int n) + { +#if NET7_0_OR_GREATER + return (n - 1 + (1 << 5)) >>> 5; +#else + return (int)((uint)(n - 1 + (1 << 5)) >> 5); +#endif + } + + /// + /// Divide by 32 and get remainder + /// + /// Number + /// Remainder + /// Quotient + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Div32Rem(int number, out int remainder) + { + var quotient = (uint)number / 32; + remainder = number & (32 - 1); + return (int)quotient; + } + + /// + /// Empty + /// + public static NativeBitArray Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBitArray.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBitArray.cs.meta new file mode 100644 index 00000000..96e72bef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBitArray.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: def81b20d63004ed795b4d605ce3d0c3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBuddyMemoryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBuddyMemoryPool.cs new file mode 100644 index 00000000..b0c16314 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBuddyMemoryPool.cs @@ -0,0 +1,227 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native buddy memory pool + /// + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeBuddyMemoryPool : IDisposable, IEquatable + { + /// + /// Min block size + /// + private readonly int _minBlockSize; + + /// + /// Max block size + /// + private readonly int _maxBlockSize; + + /// + /// Bit map + /// + private readonly int* _bitmap; + + /// + /// Memory + /// + private readonly byte* _memory; + + /// + /// Structure + /// + /// Min block size + /// Max block size + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeBuddyMemoryPool(int minBlockSize, int maxBlockSize) + { + if (minBlockSize > maxBlockSize) + throw new ArgumentException($"{minBlockSize} cannot be greater than {maxBlockSize}."); + if (minBlockSize <= 0) + throw new ArgumentOutOfRangeException(nameof(minBlockSize), minBlockSize, "MustBePositive"); + if ((minBlockSize & (minBlockSize - 1)) != 0) + throw new ArgumentOutOfRangeException(nameof(minBlockSize), minBlockSize, "MustBePowOf2"); + if ((maxBlockSize & (maxBlockSize - 1)) != 0) + throw new ArgumentOutOfRangeException(nameof(maxBlockSize), maxBlockSize, "MustBePowOf2"); + _minBlockSize = minBlockSize; + _maxBlockSize = maxBlockSize; + var bitmapSize = ((1 << (BitOperationsHelpers.Log2(maxBlockSize / minBlockSize) + 1)) + 31) / 32 * sizeof(int); + var array = (byte*)NativeMemoryAllocator.Alloc((uint)(bitmapSize + maxBlockSize)); + _bitmap = (int*)array; + _memory = array + bitmapSize; + Unsafe.InitBlockUnaligned(array, 0, (uint)bitmapSize); + } + + /// + /// Is created + /// + public bool IsCreated => _bitmap != null; + + /// + /// Min block size + /// + public int MinBlockSize => _minBlockSize; + + /// + /// Max block size + /// + public int MaxBlockSize => _maxBlockSize; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeBuddyMemoryPool other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeBuddyMemoryPool nativeBuddyMemoryPool && nativeBuddyMemoryPool == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_bitmap; + + /// + /// To string + /// + /// String + public override string ToString() => "NativeBuddyMemoryPool"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeBuddyMemoryPool left, NativeBuddyMemoryPool right) => left._bitmap == right._bitmap; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeBuddyMemoryPool left, NativeBuddyMemoryPool right) => left._bitmap != right._bitmap; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_bitmap == null) + return; + NativeMemoryAllocator.Free(_bitmap); + } + + /// + /// Get layer + /// + /// Size + /// Layer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int GetLayer(int size) => size <= _minBlockSize ? 0 : BitOperationsHelpers.Log2((uint)((size - 1) / _minBlockSize)) + 1; + + /// + /// Find free block + /// + /// Layer + /// Free block + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int FindFreeBlock(int layer) + { + var blocksInLayer = 1 << layer; + var offset = blocksInLayer - 1; + for (var i = 0; i < blocksInLayer; ++i) + { + var index = offset + i; + if ((_bitmap[index / 32] & (1 << (index % 32))) == 0) + return index; + } + + return -1; + } + + /// + /// Merge blocks + /// + /// Layer + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void MergeBlocks(int layer, int index) + { + while (layer != 0) + { + var buddyIndex = index % 2 == 0 ? index + 1 : index - 1; + var bitMask = buddyIndex % 32; + ref var segment = ref _bitmap[buddyIndex / 32]; + if ((segment & (1 << bitMask)) != 0) + break; + var parentIndex = index / 2 + ((1 << (layer - 1)) - 1); + (*(_bitmap + index / 32)) &= ~(1 << (index % 32)); + segment &= ~(1 << bitMask); + (*(_bitmap + parentIndex / 32)) |= 1 << (parentIndex % 32); + --layer; + index = parentIndex; + } + } + + /// + /// Rent buffer + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void* Rent(int size) + { + if (size > _maxBlockSize) + throw new ArgumentOutOfRangeException(nameof(size), $"{size} cannot be greater than {_maxBlockSize}."); + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size), size, "MustBePositive"); + var layer = GetLayer(size); + var blockIndex = FindFreeBlock(layer); + if (blockIndex == -1) + return null; + _bitmap[blockIndex / 32] |= 1 << (blockIndex % 32); + return _memory + (_minBlockSize << layer) * (blockIndex - ((1 << layer) - 1)); + } + + /// + /// Return buffer + /// + /// Pointer + /// Size + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(void* ptr, int size) + { + if (size > _maxBlockSize) + throw new ArgumentOutOfRangeException(nameof(size), $"{size} cannot be greater than {_maxBlockSize}."); + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size), size, "MustBePositive"); + var layer = GetLayer(size); + var blockIndex = (int)((byte*)ptr - _memory) / (_minBlockSize << layer) + ((1 << layer) - 1); + _bitmap[blockIndex / 32] &= ~(1 << (blockIndex % 32)); + MergeBlocks(layer, blockIndex); + } + + /// + /// Empty + /// + public static NativeBuddyMemoryPool Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBuddyMemoryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBuddyMemoryPool.cs.meta new file mode 100644 index 00000000..cbf44d9f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeBuddyMemoryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b90a427863934c509f20fdc258b14f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentDictionary.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentDictionary.cs new file mode 100644 index 00000000..ae09294f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentDictionary.cs @@ -0,0 +1,1458 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +using System.Collections.Generic; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native concurrentDictionary + /// (Slower than ConcurrentDictionary) + /// + /// Type + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeConcurrentDictionary : IDisposable, IEquatable> where TKey : unmanaged, IEquatable where TValue : unmanaged, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeConcurrentDictionaryHandle + { + /// + /// Tables + /// + public volatile Tables* Tables; + + /// + /// Budget + /// + public int Budget; + + /// + /// Grow lock array + /// + public bool GrowLockArray; + + /// + /// Node pool + /// + public NativeMemoryPool NodePool; + + /// + /// Node lock + /// + public NativeConcurrentSpinLock NodeLock; + + /// + /// Keys + /// + public KeyCollection Keys; + + /// + /// Values + /// + public ValueCollection Values; + } + + /// + /// Handle + /// + private readonly NativeConcurrentDictionaryHandle* _handle; + + /// + /// Keys + /// + public KeyCollection Keys => _handle->Keys; + + /// + /// Values + /// + public ValueCollection Values => _handle->Values; + + /// + /// Structure + /// + /// Size + /// Max free slabs + /// Concurrency level + /// Capacity + /// Grow lock array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeConcurrentDictionary(int size, int maxFreeSlabs, int concurrencyLevel, int capacity, bool growLockArray) + { + var nodePool = new NativeMemoryPool(size, sizeof(Node), maxFreeSlabs); + if (concurrencyLevel <= 0) + concurrencyLevel = Environment.ProcessorCount; + if (capacity < concurrencyLevel) + capacity = concurrencyLevel; + capacity = HashHelpers.GetPrime(capacity); + var locks = new NativeArrayReference(concurrencyLevel); + for (var i = 0; i < locks.Length; ++i) + locks[i] = new object(); + var countPerLock = new NativeArray(locks.Length, true); + var buckets = new NativeArray(capacity, true); + _handle = (NativeConcurrentDictionaryHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeConcurrentDictionaryHandle)); + _handle->Tables = (Tables*)NativeMemoryAllocator.Alloc((uint)sizeof(Tables)); + _handle->Tables->Initialize(buckets, locks, countPerLock); + _handle->GrowLockArray = growLockArray; + _handle->Budget = buckets.Length / locks.Length; + _handle->NodePool = nodePool; + _handle->NodeLock = new NativeConcurrentSpinLock(-1); + _handle->Keys = new KeyCollection(this); + _handle->Values = new ValueCollection(this); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is created + /// + public bool IsEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (!AreAllBucketsEmpty()) + return false; + var locksAcquired = 0; + try + { + AcquireAllLocks(ref locksAcquired); + return AreAllBucketsEmpty(); + } + finally + { + ReleaseLocks(locksAcquired); + } + } + } + + /// + /// Get or set value + /// + /// Key + public TValue this[in TKey key] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (!TryGetValue(key, out var value)) + throw new KeyNotFoundException(key.ToString()); + return value; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => TryAddInternal(_handle->Tables, key, value, true, true, out _); + } + + /// + /// Count + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var locksAcquired = 0; + try + { + AcquireAllLocks(ref locksAcquired); + return GetCountNoLocks(); + } + finally + { + ReleaseLocks(locksAcquired); + } + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeConcurrentDictionary other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeConcurrentDictionary nativeConcurrentDictionary && nativeConcurrentDictionary == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeConcurrentDictionary<{typeof(TKey).Name}, {typeof(TValue).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeConcurrentDictionary left, NativeConcurrentDictionary right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeConcurrentDictionary left, NativeConcurrentDictionary right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + _handle->Tables->Dispose(); + _handle->NodePool.Dispose(); + _handle->NodeLock.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + var locksAcquired = 0; + try + { + AcquireAllLocks(ref locksAcquired); + if (AreAllBucketsEmpty()) + return; + foreach (var bucket in _handle->Tables->Buckets) + { + var node = (Node*)bucket.Node; + while (node != null) + { + var temp = node; + node = node->Next; + _handle->NodePool.Return(temp); + } + } + + var length = HashHelpers.GetPrime(31); + if (_handle->Tables->Buckets.Length != length) + { + _handle->Tables->Buckets.Dispose(); + _handle->Tables->Buckets = new NativeArray(length, true); + } + else + { + _handle->Tables->Buckets.Clear(); + } + + _handle->Tables->CountPerLock.Clear(); + var budget = _handle->Tables->Buckets.Length / _handle->Tables->Locks.Length; + _handle->Budget = budget >= 1 ? budget : 1; + } + finally + { + ReleaseLocks(locksAcquired); + } + } + + /// + /// Try add + /// + /// Key + /// Value + /// Added + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryAdd(in TKey key, in TValue value) => TryAddInternal(_handle->Tables, key, value, false, true, out _); + + /// + /// Try remove + /// + /// Key + /// Value + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryRemove(in TKey key, out TValue value) + { + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + while (true) + { + var locks = tables->Locks; + ref var bucket = ref GetBucketAndLock(tables, hashCode, out var lockNo); + if (tables->CountPerLock[lockNo] != 0) + { + Monitor.Enter(locks[lockNo]); + try + { + if (tables != _handle->Tables) + { + tables = _handle->Tables; + continue; + } + + Node* prev = null; + for (var curr = (Node*)bucket; curr != null; curr = curr->Next) + { + if (hashCode == curr->HashCode && curr->Key.Equals(key)) + { + if (prev == null) + Volatile.Write(ref bucket, (nint)curr->Next); + else + prev->Next = curr->Next; + value = curr->Value; + _handle->NodeLock.Enter(); + try + { + _handle->NodePool.Return(curr); + } + finally + { + _handle->NodeLock.Exit(); + } + + tables->CountPerLock[lockNo]--; + return true; + } + + prev = curr; + } + } + finally + { + Monitor.Exit(locks[lockNo]); + } + } + + value = default; + return false; + } + } + + /// + /// Try remove + /// + /// Key value pair + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryRemove(in KeyValuePair keyValuePair) + { + var key = keyValuePair.Key; + var oldValue = keyValuePair.Value; + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + while (true) + { + var locks = tables->Locks; + ref var bucket = ref GetBucketAndLock(tables, hashCode, out var lockNo); + if (tables->CountPerLock[lockNo] != 0) + { + Monitor.Enter(locks[lockNo]); + try + { + if (tables != _handle->Tables) + { + tables = _handle->Tables; + continue; + } + + Node* prev = null; + for (var curr = (Node*)bucket; curr != null; curr = curr->Next) + { + if (hashCode == curr->HashCode && curr->Key.Equals(key)) + { + if (!oldValue.Equals(curr->Value)) + return false; + if (prev == null) + Volatile.Write(ref bucket, (nint)curr->Next); + else + prev->Next = curr->Next; + _handle->NodeLock.Enter(); + try + { + _handle->NodePool.Return(curr); + } + finally + { + _handle->NodeLock.Exit(); + } + + tables->CountPerLock[lockNo]--; + return true; + } + + prev = curr; + } + } + finally + { + Monitor.Exit(locks[lockNo]); + } + } + + return false; + } + } + + /// + /// Contains key + /// + /// Key + /// Contains key + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(in TKey key) + { + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + for (var node = (Node*)GetBucket(tables, hashCode); node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + return true; + } + + return false; + } + + /// + /// Try to get the value + /// + /// Key + /// Value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in TKey key, out TValue value) + { + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + for (var node = (Node*)GetBucket(tables, hashCode); node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + { + value = node->Value; + return true; + } + } + + value = default; + return false; + } + + /// + /// Try update + /// + /// Key + /// New value + /// Comparison value + /// Updated + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryUpdate(in TKey key, in TValue newValue, in TValue comparisonValue) => TryUpdateInternal(_handle->Tables, key, newValue, comparisonValue); + + /// + /// Get or add value + /// + /// Key + /// Value + /// Value + public TValue GetOrAdd(in TKey key, in TValue value) + { + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + if (!TryGetValueInternal(tables, key, hashCode, out var resultingValue)) + TryAddInternal(tables, key, value, false, true, out resultingValue); + return resultingValue; + } + + /// + /// Check all buckets are empty + /// + /// All buckets are empty + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool AreAllBucketsEmpty() + { +#if NET8_0_OR_GREATER + return !_handle->Tables->CountPerLock.AsSpan().ContainsAnyExcept(0); +#elif NET7_0_OR_GREATER + return !(_handle->Tables->CountPerLock.AsSpan().IndexOfAnyExcept(0) >= 0); +#else + for (var i = 0; i < _handle->Tables->CountPerLock.Length; ++i) + { + if (_handle->Tables->CountPerLock[i] != 0) + return false; + } + + return true; +#endif + } + + /// + /// Grow table + /// + /// Tables + /// Resize desired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void GrowTable(Tables* tables, bool resizeDesired) + { + var locksAcquired = 0; + try + { + AcquireFirstLock(ref locksAcquired); + if (tables != _handle->Tables) + return; + var newLength = tables->Buckets.Length; + if (resizeDesired) + { + if (GetCountNoLocks() < tables->Buckets.Length / 4) + { + _handle->Budget = 2 * _handle->Budget; + if (_handle->Budget < 0) + _handle->Budget = int.MaxValue; + return; + } + + if ((newLength = tables->Buckets.Length * 2) < 0 || (newLength = HashHelpers.GetPrime(newLength)) > 2147483591) + { + newLength = 2147483591; + _handle->Budget = int.MaxValue; + } + } + + var newLocks = tables->Locks; + if (_handle->GrowLockArray && tables->Locks.Length < 1024) + { + newLocks = new NativeArrayReference(tables->Locks.Length * 2); + Array.Copy(tables->Locks.Array, newLocks.Array, tables->Locks.Length); + for (var i = tables->Locks.Length; i < newLocks.Length; ++i) + newLocks[i] = new NativeMonitorLock(new object()); + } + + var newBuckets = new NativeArray(newLength, true); + var newCountPerLock = new NativeArray(newLocks.Length, true); + var newTables = (Tables*)NativeMemoryAllocator.Alloc((uint)sizeof(Tables)); + newTables->Initialize(newBuckets, newLocks, newCountPerLock); + AcquirePostFirstLock(tables, ref locksAcquired); + foreach (var bucket in tables->Buckets) + { + var current = (Node*)bucket.Node; + while (current != null) + { + var hashCode = current->HashCode; + var next = current->Next; + ref var newBucket = ref GetBucketAndLock(newTables, hashCode, out var newLockNo); + var newNode = current; + newNode->Initialize(current->Key, current->Value, hashCode, (Node*)newBucket); + newBucket = (nint)newNode; + checked + { + newCountPerLock[newLockNo]++; + } + + current = next; + } + } + + var budget = newBuckets.Length / newLocks.Length; + _handle->Budget = budget >= 1 ? budget : 1; + _handle->Tables->Buckets.Dispose(); + if (_handle->Tables->Locks != newLocks) + _handle->Tables->Locks.Dispose(); + _handle->Tables->CountPerLock.Dispose(); + NativeMemoryAllocator.Free(_handle->Tables); + _handle->Tables = newTables; + } + finally + { + ReleaseLocks(locksAcquired); + } + } + + /// + /// Acquire all locks + /// + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void AcquireAllLocks(ref int locksAcquired) + { + AcquireFirstLock(ref locksAcquired); + AcquirePostFirstLock(_handle->Tables, ref locksAcquired); + } + + /// + /// Acquire first lock + /// + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void AcquireFirstLock(ref int locksAcquired) + { + var locks = _handle->Tables->Locks; + Monitor.Enter(locks[0]); + locksAcquired = 1; + } + + /// + /// Acquire post first locks + /// + /// Tables + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AcquirePostFirstLock(Tables* tables, ref int locksAcquired) + { + var locks = tables->Locks; + for (var i = 1; i < locks.Length; ++i) + { + Monitor.Enter(locks[i]); + locksAcquired++; + } + } + + /// + /// Release locks + /// + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReleaseLocks(int locksAcquired) + { + var locks = _handle->Tables->Locks; + for (var i = 0; i < locksAcquired; ++i) + Monitor.Exit(locks[i]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool TryAddInternal(Tables* tables, in TKey key, in TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue) + { + var hashCode = key.GetHashCode(); + while (true) + { + var locks = tables->Locks; + ref var bucket = ref GetBucketAndLock(tables, hashCode, out var lockNo); + var resizeDesired = false; + var lockTaken = false; + try + { + if (acquireLock) + Monitor.Enter(locks[lockNo], ref lockTaken); + if (tables != _handle->Tables) + { + tables = _handle->Tables; + continue; + } + + Node* prev = null; + for (var node = (Node*)bucket; node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + { + if (updateIfExists) + { + if (NativeConcurrentDictionaryTypeProps.IsWriteAtomic) + { + node->Value = value; + } + else + { + Node* newNode; + _handle->NodeLock.Enter(); + try + { + newNode = (Node*)_handle->NodePool.Rent(); + } + finally + { + _handle->NodeLock.Exit(); + } + + newNode->Initialize(node->Key, value, hashCode, node->Next); + if (prev == null) + Volatile.Write(ref bucket, (nint)newNode); + else + prev->Next = newNode; + _handle->NodeLock.Enter(); + try + { + _handle->NodePool.Return(node); + } + finally + { + _handle->NodeLock.Exit(); + } + } + + resultingValue = value; + } + else + { + resultingValue = node->Value; + } + + return false; + } + + prev = node; + } + + Node* resultNode; + _handle->NodeLock.Enter(); + try + { + resultNode = (Node*)_handle->NodePool.Rent(); + } + finally + { + _handle->NodeLock.Exit(); + } + + resultNode->Initialize(key, value, hashCode, (Node*)bucket); + Volatile.Write(ref bucket, (nint)resultNode); + checked + { + tables->CountPerLock[lockNo]++; + } + + if (tables->CountPerLock[lockNo] > _handle->Budget) + resizeDesired = true; + } + finally + { + if (lockTaken) + Monitor.Exit(locks[lockNo]); + } + + if (resizeDesired) + GrowTable(tables, resizeDesired); + resultingValue = value; + return true; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool TryUpdateInternal(Tables* tables, in TKey key, in TValue newValue, in TValue comparisonValue) + { + var hashCode = key.GetHashCode(); + while (true) + { + var locks = tables->Locks; + ref var bucket = ref GetBucketAndLock(tables, hashCode, out var lockNo); + Monitor.Enter(locks[lockNo]); + try + { + if (tables != _handle->Tables) + { + tables = _handle->Tables; + continue; + } + + Node* prev = null; + for (var node = (Node*)bucket; node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + { + if (node->Value.Equals(comparisonValue)) + { + if (NativeConcurrentDictionaryTypeProps.IsWriteAtomic) + { + node->Value = newValue; + } + else + { + Node* newNode; + _handle->NodeLock.Enter(); + try + { + newNode = (Node*)_handle->NodePool.Rent(); + } + finally + { + _handle->NodeLock.Exit(); + } + + newNode->Initialize(node->Key, newValue, hashCode, node->Next); + if (prev == null) + Volatile.Write(ref bucket, (nint)newNode); + else + prev->Next = newNode; + _handle->NodeLock.Enter(); + try + { + _handle->NodePool.Return(node); + } + finally + { + _handle->NodeLock.Exit(); + } + } + + return true; + } + + return false; + } + + prev = node; + } + + return false; + } + finally + { + Monitor.Exit(locks[lockNo]); + } + } + } + + /// + /// Try to get the value + /// + /// Tables + /// Key + /// HashCode + /// Value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryGetValueInternal(Tables* tables, in TKey key, int hashCode, out TValue value) + { + for (var node = (Node*)GetBucket(tables, hashCode); node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + { + value = node->Value; + return true; + } + } + + value = default; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int GetCountNoLocks() + { + var count = 0; + foreach (var value in _handle->Tables->CountPerLock) + { + checked + { + count += value; + } + } + + return count; + } + + /// + /// Get bucket + /// + /// Tables + /// HashCode + /// Bucket + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static nint GetBucket(Tables* tables, int hashCode) + { + var buckets = tables->Buckets; + return IntPtr.Size == 8 ? buckets[HashHelpers.FastMod((uint)hashCode, (uint)buckets.Length, tables->FastModBucketsMultiplier)].Node : buckets[(uint)hashCode % (uint)buckets.Length].Node; + } + + /// + /// Get bucket and lock + /// + /// Tables + /// HashCode + /// Lock no + /// Bucket + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static ref nint GetBucketAndLock(Tables* tables, int hashCode, out uint lockNo) + { + var buckets = tables->Buckets; + var bucketNo = IntPtr.Size == 8 ? HashHelpers.FastMod((uint)hashCode, (uint)buckets.Length, tables->FastModBucketsMultiplier) : (uint)hashCode % (uint)buckets.Length; + lockNo = bucketNo % (uint)tables->Locks.Length; + return ref buckets[bucketNo].Node; + } + + /// + /// Volatile node + /// + private struct VolatileNode + { + /// + /// Node + /// + public volatile nint Node; + } + + /// + /// Node + /// + private struct Node + { + /// + /// Key + /// + public TKey Key; + + /// + /// Value + /// + public TValue Value; + + /// + /// Next + /// + public volatile Node* Next; + + /// + /// HashCode + /// + public int HashCode; + + /// + /// Initialize + /// + /// Key + /// Value + /// HashCode + /// Next + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(in TKey key, in TValue value, int hashCode, Node* next) + { + Key = key; + Value = value; + Next = next; + HashCode = hashCode; + } + } + + /// + /// Tables + /// + private struct Tables + { + /// + /// Buckets + /// + public NativeArray Buckets; + + /// + /// Fast mod buckets multiplier + /// + public ulong FastModBucketsMultiplier; + + /// + /// Locks + /// + public NativeArrayReference Locks; + + /// + /// Count per lock + /// + public NativeArray CountPerLock; + + /// + /// Initialize + /// + /// Buckets + /// Locks + /// Count per lock + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(in NativeArray buckets, in NativeArrayReference locks, in NativeArray countPerLock) + { + Buckets = buckets; + Locks = locks; + CountPerLock = countPerLock; + FastModBucketsMultiplier = IntPtr.Size == 8 ? HashHelpers.GetFastModMultiplier((uint)buckets.Length) : 0; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + Buckets.Dispose(); + Locks.Dispose(); + CountPerLock.Dispose(); + } + } + + /// + /// Empty + /// + public static NativeConcurrentDictionary Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeConcurrentDictionary + /// + private readonly NativeConcurrentDictionary _nativeConcurrentDictionary; + + /// + /// Buckets + /// + private NativeArray _buckets; + + /// + /// Node + /// + private Node* _node; + + /// + /// Index + /// + private int _index; + + /// + /// State + /// + private int _state; + + /// + /// State uninitialized + /// + private const int STATE_UNINITIALIZED = 0; + + /// + /// State outer loop + /// + private const int STATE_OUTER_LOOP = 1; + + /// + /// State inner loop + /// + private const int STATE_INNER_LOOP = 2; + + /// + /// State done + /// + private const int STATE_DONE = 3; + + /// + /// Current + /// + private KeyValuePair _current; + + /// + /// Structure + /// + /// NativeConcurrentDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeConcurrentDictionary nativeConcurrentDictionary) + { + _nativeConcurrentDictionary = nativeConcurrentDictionary; + _index = -1; + _buckets = default; + _node = null; + _state = 0; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + switch (_state) + { + case STATE_UNINITIALIZED: + _buckets = _nativeConcurrentDictionary._handle->Tables->Buckets; + _index = -1; + goto case STATE_OUTER_LOOP; + case STATE_OUTER_LOOP: + var buckets = _buckets; + var i = ++_index; + if ((uint)i < (uint)buckets.Length) + { + _node = (Node*)buckets[i].Node; + _state = STATE_INNER_LOOP; + goto case STATE_INNER_LOOP; + } + + goto default; + case STATE_INNER_LOOP: + if (_node != null) + { + var node = _node; + _current = new KeyValuePair(node->Key, node->Value); + _node = node->Next; + return true; + } + + goto case STATE_OUTER_LOOP; + default: + _state = STATE_DONE; + return false; + } + } + + /// + /// Current + /// + public KeyValuePair Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + + /// + /// Key collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct KeyCollection + { + /// + /// NativeConcurrentDictionary + /// + private readonly NativeConcurrentDictionary _nativeConcurrentDictionary; + + /// + /// Structure + /// + /// NativeConcurrentDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal KeyCollection(in NativeConcurrentDictionary nativeConcurrentDictionary) => _nativeConcurrentDictionary = nativeConcurrentDictionary; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeConcurrentDictionary); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeConcurrentDictionary + /// + private readonly NativeConcurrentDictionary _nativeConcurrentDictionary; + + /// + /// Buckets + /// + private NativeArray _buckets; + + /// + /// Node + /// + private Node* _node; + + /// + /// Index + /// + private int _index; + + /// + /// State + /// + private int _state; + + /// + /// State uninitialized + /// + private const int STATE_UNINITIALIZED = 0; + + /// + /// State outer loop + /// + private const int STATE_OUTER_LOOP = 1; + + /// + /// State inner loop + /// + private const int STATE_INNER_LOOP = 2; + + /// + /// State done + /// + private const int STATE_DONE = 3; + + /// + /// Current + /// + private TKey _current; + + /// + /// Structure + /// + /// NativeConcurrentDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeConcurrentDictionary nativeConcurrentDictionary) + { + _nativeConcurrentDictionary = nativeConcurrentDictionary; + _index = -1; + _buckets = default; + _node = null; + _state = 0; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + switch (_state) + { + case STATE_UNINITIALIZED: + _buckets = _nativeConcurrentDictionary._handle->Tables->Buckets; + _index = -1; + goto case STATE_OUTER_LOOP; + case STATE_OUTER_LOOP: + var buckets = _buckets; + var i = ++_index; + if ((uint)i < (uint)buckets.Length) + { + _node = (Node*)buckets[i].Node; + _state = STATE_INNER_LOOP; + goto case STATE_INNER_LOOP; + } + + goto default; + case STATE_INNER_LOOP: + if (_node != null) + { + var node = _node; + _current = node->Key; + _node = node->Next; + return true; + } + + goto case STATE_OUTER_LOOP; + default: + _state = STATE_DONE; + return false; + } + } + + /// + /// Current + /// + public TKey Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } + + /// + /// Value collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct ValueCollection + { + /// + /// NativeConcurrentDictionary + /// + private readonly NativeConcurrentDictionary _nativeConcurrentDictionary; + + /// + /// Structure + /// + /// NativeConcurrentDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ValueCollection(in NativeConcurrentDictionary nativeConcurrentDictionary) => _nativeConcurrentDictionary = nativeConcurrentDictionary; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeConcurrentDictionary); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeConcurrentDictionary + /// + private readonly NativeConcurrentDictionary _nativeConcurrentDictionary; + + /// + /// Buckets + /// + private NativeArray _buckets; + + /// + /// Node + /// + private Node* _node; + + /// + /// Index + /// + private int _index; + + /// + /// State + /// + private int _state; + + /// + /// State uninitialized + /// + private const int STATE_UNINITIALIZED = 0; + + /// + /// State outer loop + /// + private const int STATE_OUTER_LOOP = 1; + + /// + /// State inner loop + /// + private const int STATE_INNER_LOOP = 2; + + /// + /// State done + /// + private const int STATE_DONE = 3; + + /// + /// Current + /// + private TValue _current; + + /// + /// Structure + /// + /// NativeConcurrentDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeConcurrentDictionary nativeConcurrentDictionary) + { + _nativeConcurrentDictionary = nativeConcurrentDictionary; + _index = -1; + _buckets = default; + _node = null; + _state = 0; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + switch (_state) + { + case STATE_UNINITIALIZED: + _buckets = _nativeConcurrentDictionary._handle->Tables->Buckets; + _index = -1; + goto case STATE_OUTER_LOOP; + case STATE_OUTER_LOOP: + var buckets = _buckets; + var i = ++_index; + if ((uint)i < (uint)buckets.Length) + { + _node = (Node*)buckets[i].Node; + _state = STATE_INNER_LOOP; + goto case STATE_INNER_LOOP; + } + + goto default; + case STATE_INNER_LOOP: + if (_node != null) + { + var node = _node; + _current = node->Value; + _node = node->Next; + return true; + } + + goto case STATE_OUTER_LOOP; + default: + _state = STATE_DONE; + return false; + } + } + + /// + /// Current + /// + public TValue Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } + } + + /// + /// Native concurrentDictionary type props + /// + /// Type + internal static class NativeConcurrentDictionaryTypeProps where T : unmanaged, IEquatable + { + /// + /// Is write atomic + /// + public static readonly bool IsWriteAtomic = IsWriteAtomicPrivate(); + + /// + /// Is write atomic + /// + /// Is write atomic + private static bool IsWriteAtomicPrivate() + { + if (typeof(T) == typeof(IntPtr) || typeof(T) == typeof(UIntPtr)) + return true; + switch (Type.GetTypeCode(typeof(T))) + { + case TypeCode.Boolean: + case TypeCode.Byte: + case TypeCode.Char: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.SByte: + case TypeCode.Single: + case TypeCode.UInt16: + case TypeCode.UInt32: + return true; + case TypeCode.Double: + case TypeCode.Int64: + case TypeCode.UInt64: + return IntPtr.Size == 8; + default: + return false; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentDictionary.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentDictionary.cs.meta new file mode 100644 index 00000000..b5ea2aa0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 148579b61de314722b9c426d716b6ec3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentHashSet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentHashSet.cs new file mode 100644 index 00000000..1bfb7b3c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentHashSet.cs @@ -0,0 +1,878 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native concurrentHashSet + /// (Slower than ConcurrentHashSet) + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeConcurrentHashSet : IDisposable, IEquatable> where T : unmanaged, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeConcurrentHashSetHandle + { + /// + /// Tables + /// + public volatile Tables* Tables; + + /// + /// Budget + /// + public int Budget; + + /// + /// Grow lock array + /// + public bool GrowLockArray; + + /// + /// Node pool + /// + public NativeMemoryPool NodePool; + + /// + /// Node lock + /// + public NativeConcurrentSpinLock NodeLock; + } + + /// + /// Handle + /// + private readonly NativeConcurrentHashSetHandle* _handle; + + /// + /// Structure + /// + /// Size + /// Max free slabs + /// Concurrency level + /// Capacity + /// Grow lock array + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeConcurrentHashSet(int size, int maxFreeSlabs, int concurrencyLevel, int capacity, bool growLockArray) + { + var nodePool = new NativeMemoryPool(size, sizeof(Node), maxFreeSlabs); + if (concurrencyLevel <= 0) + concurrencyLevel = Environment.ProcessorCount; + if (capacity < concurrencyLevel) + capacity = concurrencyLevel; + capacity = HashHelpers.GetPrime(capacity); + var locks = new NativeArrayReference(concurrencyLevel); + for (var i = 0; i < locks.Length; ++i) + locks[i] = new object(); + var countPerLock = new NativeArray(locks.Length, true); + var buckets = new NativeArray(capacity, true); + _handle = (NativeConcurrentHashSetHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeConcurrentHashSetHandle)); + _handle->Tables = (Tables*)NativeMemoryAllocator.Alloc((uint)sizeof(Tables)); + _handle->Tables->Initialize(buckets, locks, countPerLock); + _handle->GrowLockArray = growLockArray; + _handle->Budget = buckets.Length / locks.Length; + _handle->NodePool = nodePool; + _handle->NodeLock = new NativeConcurrentSpinLock(-1); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is created + /// + public bool IsEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (!AreAllBucketsEmpty()) + return false; + var locksAcquired = 0; + try + { + AcquireAllLocks(ref locksAcquired); + return AreAllBucketsEmpty(); + } + finally + { + ReleaseLocks(locksAcquired); + } + } + } + + /// + /// Count + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var locksAcquired = 0; + try + { + AcquireAllLocks(ref locksAcquired); + return GetCountNoLocks(); + } + finally + { + ReleaseLocks(locksAcquired); + } + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeConcurrentHashSet other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeConcurrentHashSet nativeConcurrentHashSet && nativeConcurrentHashSet == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeConcurrentHashSet<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeConcurrentHashSet left, NativeConcurrentHashSet right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeConcurrentHashSet left, NativeConcurrentHashSet right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + _handle->Tables->Dispose(); + _handle->NodePool.Dispose(); + _handle->NodeLock.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + var locksAcquired = 0; + try + { + AcquireAllLocks(ref locksAcquired); + if (AreAllBucketsEmpty()) + return; + foreach (var bucket in _handle->Tables->Buckets) + { + var node = (Node*)bucket.Node; + while (node != null) + { + var temp = node; + node = node->Next; + _handle->NodePool.Return(temp); + } + } + + var length = HashHelpers.GetPrime(31); + if (_handle->Tables->Buckets.Length != length) + { + _handle->Tables->Buckets.Dispose(); + _handle->Tables->Buckets = new NativeArray(length, true); + } + else + { + _handle->Tables->Buckets.Clear(); + } + + _handle->Tables->CountPerLock.Clear(); + var budget = _handle->Tables->Buckets.Length / _handle->Tables->Locks.Length; + _handle->Budget = budget >= 1 ? budget : 1; + } + finally + { + ReleaseLocks(locksAcquired); + } + } + + /// + /// Add + /// + /// Key + /// Added + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Add(in T key) => TryAddInternal(_handle->Tables, key); + + /// + /// Remove + /// + /// Key + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in T key) + { + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + while (true) + { + var locks = tables->Locks; + ref var bucket = ref GetBucketAndLock(tables, hashCode, out var lockNo); + if (tables->CountPerLock[lockNo] != 0) + { + Monitor.Enter(locks[lockNo]); + try + { + if (tables != _handle->Tables) + { + tables = _handle->Tables; + continue; + } + + Node* prev = null; + for (var curr = (Node*)bucket; curr != null; curr = curr->Next) + { + if (hashCode == curr->HashCode && curr->Key.Equals(key)) + { + if (prev == null) + Volatile.Write(ref bucket, (nint)curr->Next); + else + prev->Next = curr->Next; + _handle->NodeLock.Enter(); + try + { + _handle->NodePool.Return(curr); + } + finally + { + _handle->NodeLock.Exit(); + } + + tables->CountPerLock[lockNo]--; + return true; + } + + prev = curr; + } + } + finally + { + Monitor.Exit(locks[lockNo]); + } + } + + return false; + } + } + + /// + /// Contains key + /// + /// Key + /// Contains key + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(in T key) + { + var tables = _handle->Tables; + var hashCode = key.GetHashCode(); + for (var node = (Node*)GetBucket(tables, hashCode); node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + return true; + } + + return false; + } + + /// + /// Try to get the actual value + /// + /// Equal value + /// Actual value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in T equalValue, out T actualValue) + { + var tables = _handle->Tables; + var hashCode = equalValue.GetHashCode(); + for (var node = (Node*)GetBucket(tables, hashCode); node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(equalValue)) + { + actualValue = node->Key; + return true; + } + } + + actualValue = default; + return false; + } + + /// + /// Check all buckets are empty + /// + /// All buckets are empty + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool AreAllBucketsEmpty() + { +#if NET8_0_OR_GREATER + return !_handle->Tables->CountPerLock.AsSpan().ContainsAnyExcept(0); +#elif NET7_0_OR_GREATER + return !(_handle->Tables->CountPerLock.AsSpan().IndexOfAnyExcept(0) >= 0); +#else + for (var i = 0; i < _handle->Tables->CountPerLock.Length; ++i) + { + if (_handle->Tables->CountPerLock[i] != 0) + return false; + } + + return true; +#endif + } + + /// + /// Grow table + /// + /// Tables + /// Resize desired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void GrowTable(Tables* tables, bool resizeDesired) + { + var locksAcquired = 0; + try + { + AcquireFirstLock(ref locksAcquired); + if (tables != _handle->Tables) + return; + var newLength = tables->Buckets.Length; + if (resizeDesired) + { + if (GetCountNoLocks() < tables->Buckets.Length / 4) + { + _handle->Budget = 2 * _handle->Budget; + if (_handle->Budget < 0) + _handle->Budget = int.MaxValue; + return; + } + + if ((newLength = tables->Buckets.Length * 2) < 0 || (newLength = HashHelpers.GetPrime(newLength)) > 2147483591) + { + newLength = 2147483591; + _handle->Budget = int.MaxValue; + } + } + + var newLocks = tables->Locks; + if (_handle->GrowLockArray && tables->Locks.Length < 1024) + { + newLocks = new NativeArrayReference(tables->Locks.Length * 2); + Array.Copy(tables->Locks.Array, newLocks.Array, tables->Locks.Length); + for (var i = tables->Locks.Length; i < newLocks.Length; ++i) + newLocks[i] = new NativeMonitorLock(new object()); + } + + var newBuckets = new NativeArray(newLength, true); + var newCountPerLock = new NativeArray(newLocks.Length, true); + var newTables = (Tables*)NativeMemoryAllocator.Alloc((uint)sizeof(Tables)); + newTables->Initialize(newBuckets, newLocks, newCountPerLock); + AcquirePostFirstLock(tables, ref locksAcquired); + foreach (var bucket in tables->Buckets) + { + var current = (Node*)bucket.Node; + while (current != null) + { + var hashCode = current->HashCode; + var next = current->Next; + ref var newBucket = ref GetBucketAndLock(newTables, hashCode, out var newLockNo); + var newNode = current; + newNode->Initialize(current->Key, hashCode, (Node*)newBucket); + newBucket = (nint)newNode; + checked + { + newCountPerLock[newLockNo]++; + } + + current = next; + } + } + + var budget = newBuckets.Length / newLocks.Length; + _handle->Budget = budget >= 1 ? budget : 1; + _handle->Tables->Buckets.Dispose(); + if (_handle->Tables->Locks != newLocks) + _handle->Tables->Locks.Dispose(); + _handle->Tables->CountPerLock.Dispose(); + NativeMemoryAllocator.Free(_handle->Tables); + _handle->Tables = newTables; + } + finally + { + ReleaseLocks(locksAcquired); + } + } + + /// + /// Acquire all locks + /// + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void AcquireAllLocks(ref int locksAcquired) + { + AcquireFirstLock(ref locksAcquired); + AcquirePostFirstLock(_handle->Tables, ref locksAcquired); + } + + /// + /// Acquire first lock + /// + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void AcquireFirstLock(ref int locksAcquired) + { + var locks = _handle->Tables->Locks; + Monitor.Enter(locks[0]); + locksAcquired = 1; + } + + /// + /// Acquire post first locks + /// + /// Tables + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AcquirePostFirstLock(Tables* tables, ref int locksAcquired) + { + var locks = tables->Locks; + for (var i = 1; i < locks.Length; ++i) + { + Monitor.Enter(locks[i]); + locksAcquired++; + } + } + + /// + /// Release locks + /// + /// Locks acquired + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReleaseLocks(int locksAcquired) + { + var locks = _handle->Tables->Locks; + for (var i = 0; i < locksAcquired; ++i) + Monitor.Exit(locks[i]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool TryAddInternal(Tables* tables, in T key) + { + var hashCode = key.GetHashCode(); + while (true) + { + var locks = tables->Locks; + ref var bucket = ref GetBucketAndLock(tables, hashCode, out var lockNo); + var resizeDesired = false; + var lockTaken = false; + try + { + Monitor.Enter(locks[lockNo], ref lockTaken); + if (tables != _handle->Tables) + { + tables = _handle->Tables; + continue; + } + + for (var node = (Node*)bucket; node != null; node = node->Next) + { + if (hashCode == node->HashCode && node->Key.Equals(key)) + return false; + } + + Node* resultNode; + _handle->NodeLock.Enter(); + try + { + resultNode = (Node*)_handle->NodePool.Rent(); + } + finally + { + _handle->NodeLock.Exit(); + } + + resultNode->Initialize(key, hashCode, (Node*)bucket); + Volatile.Write(ref bucket, (nint)resultNode); + checked + { + tables->CountPerLock[lockNo]++; + } + + if (tables->CountPerLock[lockNo] > _handle->Budget) + resizeDesired = true; + } + finally + { + if (lockTaken) + Monitor.Exit(locks[lockNo]); + } + + if (resizeDesired) + GrowTable(tables, resizeDesired); + return true; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int GetCountNoLocks() + { + var count = 0; + foreach (var value in _handle->Tables->CountPerLock) + { + checked + { + count += value; + } + } + + return count; + } + + /// + /// Get bucket + /// + /// Tables + /// HashCode + /// Bucket + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static nint GetBucket(Tables* tables, int hashCode) + { + var buckets = tables->Buckets; + return IntPtr.Size == 8 ? buckets[HashHelpers.FastMod((uint)hashCode, (uint)buckets.Length, tables->FastModBucketsMultiplier)].Node : buckets[(uint)hashCode % (uint)buckets.Length].Node; + } + + /// + /// Get bucket and lock + /// + /// Tables + /// HashCode + /// Lock no + /// Bucket + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static ref nint GetBucketAndLock(Tables* tables, int hashCode, out uint lockNo) + { + var buckets = tables->Buckets; + var bucketNo = IntPtr.Size == 8 ? HashHelpers.FastMod((uint)hashCode, (uint)buckets.Length, tables->FastModBucketsMultiplier) : (uint)hashCode % (uint)buckets.Length; + lockNo = bucketNo % (uint)tables->Locks.Length; + return ref buckets[bucketNo].Node; + } + + /// + /// Volatile node + /// + private struct VolatileNode + { + /// + /// Node + /// + public volatile nint Node; + } + + /// + /// Node + /// + private struct Node + { + /// + /// Key + /// + public T Key; + + /// + /// Next + /// + public volatile Node* Next; + + /// + /// HashCode + /// + public int HashCode; + + /// + /// Initialize + /// + /// Key + /// HashCode + /// Next + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(in T key, int hashCode, Node* next) + { + Key = key; + Next = next; + HashCode = hashCode; + } + } + + /// + /// Tables + /// + private struct Tables + { + /// + /// Buckets + /// + public NativeArray Buckets; + + /// + /// Fast mod buckets multiplier + /// + public ulong FastModBucketsMultiplier; + + /// + /// Locks + /// + public NativeArrayReference Locks; + + /// + /// Count per lock + /// + public NativeArray CountPerLock; + + /// + /// Initialize + /// + /// Buckets + /// Locks + /// Count per lock + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(in NativeArray buckets, in NativeArrayReference locks, in NativeArray countPerLock) + { + Buckets = buckets; + Locks = locks; + CountPerLock = countPerLock; + FastModBucketsMultiplier = IntPtr.Size == 8 ? HashHelpers.GetFastModMultiplier((uint)buckets.Length) : 0; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + Buckets.Dispose(); + Locks.Dispose(); + CountPerLock.Dispose(); + } + } + + /// + /// Empty + /// + public static NativeConcurrentHashSet Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeConcurrentHashSet + /// + private readonly NativeConcurrentHashSet _nativeConcurrentHashSet; + + /// + /// Buckets + /// + private NativeArray _buckets; + + /// + /// Node + /// + private Node* _node; + + /// + /// Index + /// + private int _index; + + /// + /// State + /// + private int _state; + + /// + /// State uninitialized + /// + private const int STATE_UNINITIALIZED = 0; + + /// + /// State outer loop + /// + private const int STATE_OUTER_LOOP = 1; + + /// + /// State inner loop + /// + private const int STATE_INNER_LOOP = 2; + + /// + /// State done + /// + private const int STATE_DONE = 3; + + /// + /// Current + /// + private T _current; + + /// + /// Structure + /// + /// NativeConcurrentHashSet + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeConcurrentHashSet nativeConcurrentHashSet) + { + _nativeConcurrentHashSet = nativeConcurrentHashSet; + _index = -1; + _buckets = default; + _node = null; + _state = 0; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + switch (_state) + { + case STATE_UNINITIALIZED: + _buckets = _nativeConcurrentHashSet._handle->Tables->Buckets; + _index = -1; + goto case STATE_OUTER_LOOP; + case STATE_OUTER_LOOP: + var buckets = _buckets; + var i = ++_index; + if ((uint)i < (uint)buckets.Length) + { + _node = (Node*)buckets[i].Node; + _state = STATE_INNER_LOOP; + goto case STATE_INNER_LOOP; + } + + goto default; + case STATE_INNER_LOOP: + if (_node != null) + { + var node = _node; + _current = node->Key; + _node = node->Next; + return true; + } + + goto case STATE_OUTER_LOOP; + default: + _state = STATE_DONE; + return false; + } + } + + /// + /// Current + /// + public T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } + + /// + /// Native concurrentHashSet type props + /// + /// Type + internal static class NativeConcurrentHashSetTypeProps where T : unmanaged, IEquatable + { + /// + /// Is write atomic + /// + public static readonly bool IsWriteAtomic = IsWriteAtomicPrivate(); + + /// + /// Is write atomic + /// + /// Is write atomic + private static bool IsWriteAtomicPrivate() + { + if (typeof(T) == typeof(IntPtr) || typeof(T) == typeof(UIntPtr)) + return true; + switch (Type.GetTypeCode(typeof(T))) + { + case TypeCode.Boolean: + case TypeCode.Byte: + case TypeCode.Char: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.SByte: + case TypeCode.Single: + case TypeCode.UInt16: + case TypeCode.UInt32: + return true; + case TypeCode.Double: + case TypeCode.Int64: + case TypeCode.UInt64: + return IntPtr.Size == 8; + default: + return false; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentHashSet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentHashSet.cs.meta new file mode 100644 index 00000000..cd168a93 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentHashSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 31e6b58873f1646e39361da0083d3fb2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentQueue.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentQueue.cs new file mode 100644 index 00000000..9ecc2b9f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentQueue.cs @@ -0,0 +1,1288 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native concurrentQueue + /// (Slower than ConcurrentQueue, disable Enumerator, try peek either) + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public unsafe struct NativeConcurrentQueue : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Handle + /// + private void* _handle; + + /// + /// Not arm64 + /// + private NativeConcurrentQueueNotArm64* NotArm64Handle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (NativeConcurrentQueueNotArm64*)_handle; + } + + /// + /// Arm64 + /// + private NativeConcurrentQueueArm64* Arm64Handle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (NativeConcurrentQueueArm64*)_handle; + } + + /// + /// Structure + /// + /// Size + /// Max free slabs + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeConcurrentQueue(int size, int maxFreeSlabs) + { + if (RuntimeInformation.ProcessArchitecture != Architecture.Arm64) + { + var segmentPool = new NativeMemoryPool(size, sizeof(NativeConcurrentQueueSegmentNotArm64) + NativeConcurrentQueueSegmentNotArm64.LENGTH * sizeof(NativeConcurrentQueueSegmentNotArm64.Slot), maxFreeSlabs); + _handle = NativeMemoryAllocator.Alloc((uint)sizeof(NativeConcurrentQueueNotArm64)); + NotArm64Handle->Initialize(segmentPool); + } + else + { + var segmentPool = new NativeMemoryPool(size, sizeof(NativeConcurrentQueueSegmentArm64) + NativeConcurrentQueueSegmentArm64.LENGTH * sizeof(NativeConcurrentQueueSegmentArm64.Slot), maxFreeSlabs); + _handle = NativeMemoryAllocator.Alloc((uint)sizeof(NativeConcurrentQueueArm64)); + Arm64Handle->Initialize(segmentPool); + } + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// IsEmpty + /// + public bool IsEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => RuntimeInformation.ProcessArchitecture != Architecture.Arm64 ? NotArm64Handle->IsEmpty : Arm64Handle->IsEmpty; + } + + /// + /// Count + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => RuntimeInformation.ProcessArchitecture != Architecture.Arm64 ? NotArm64Handle->Count : Arm64Handle->Count; + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeConcurrentQueue other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeConcurrentQueue nativeConcurrentQueue && nativeConcurrentQueue == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeConcurrentQueue<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeConcurrentQueue left, NativeConcurrentQueue right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeConcurrentQueue left, NativeConcurrentQueue right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + if (RuntimeInformation.ProcessArchitecture != Architecture.Arm64) + NotArm64Handle->Dispose(); + else + Arm64Handle->Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + if (RuntimeInformation.ProcessArchitecture != Architecture.Arm64) + NotArm64Handle->Clear(); + else + Arm64Handle->Clear(); + } + + /// + /// Enqueue + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enqueue(in T item) + { + if (RuntimeInformation.ProcessArchitecture != Architecture.Arm64) + NotArm64Handle->Enqueue(item); + else + Arm64Handle->Enqueue(item); + } + + /// + /// Try dequeue + /// + /// Item + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out T result) => RuntimeInformation.ProcessArchitecture != Architecture.Arm64 ? NotArm64Handle->TryDequeue(out result) : Arm64Handle->TryDequeue(out result); + + /// + /// Empty + /// + public static NativeConcurrentQueue Empty => new(); + } + + /// + /// Native concurrentQueue + /// (Slower than ConcurrentQueue, disable Enumerator, try peek either) + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct NativeConcurrentQueueNotArm64 : IDisposable where T : unmanaged + { + /// + /// Cross segment lock + /// + private NativeMonitorLock _crossSegmentLock; + + /// + /// Segment pool + /// + private NativeMemoryPool _segmentPool; + + /// + /// Tail + /// + private volatile NativeConcurrentQueueSegmentNotArm64* _tail; + + /// + /// Head + /// + private volatile NativeConcurrentQueueSegmentNotArm64* _head; + + /// + /// IsEmpty + /// + public bool IsEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var segment = _head; + while (true) + { + var next = Volatile.Read(ref segment->NextSegment); + if (segment->TryPeek()) + return false; + if (next != IntPtr.Zero) + segment = (NativeConcurrentQueueSegmentNotArm64*)next; + else if (Volatile.Read(ref segment->NextSegment) == IntPtr.Zero) + break; + } + + return true; + } + } + + /// + /// Count + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var spinCount = 0; + while (true) + { + var head = _head; + var tail = _tail; + var headHead = Volatile.Read(ref head->HeadAndTail.Head); + var headTail = Volatile.Read(ref head->HeadAndTail.Tail); + if (head == tail) + { + if (head == _head && tail == _tail && headHead == Volatile.Read(ref head->HeadAndTail.Head) && headTail == Volatile.Read(ref head->HeadAndTail.Tail)) + return GetCount(head, headHead, headTail); + } + else if ((NativeConcurrentQueueSegmentNotArm64*)head->NextSegment == tail) + { + var tailHead = Volatile.Read(ref tail->HeadAndTail.Head); + var tailTail = Volatile.Read(ref tail->HeadAndTail.Tail); + if (head == _head && tail == _tail && headHead == Volatile.Read(ref head->HeadAndTail.Head) && headTail == Volatile.Read(ref head->HeadAndTail.Tail) && tailHead == Volatile.Read(ref tail->HeadAndTail.Head) && tailTail == Volatile.Read(ref tail->HeadAndTail.Tail)) + return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); + } + else + { + _crossSegmentLock.Enter(); + try + { + if (head == _head && tail == _tail) + { + var tailHead = Volatile.Read(ref tail->HeadAndTail.Head); + var tailTail = Volatile.Read(ref tail->HeadAndTail.Tail); + if (headHead == Volatile.Read(ref head->HeadAndTail.Head) && headTail == Volatile.Read(ref head->HeadAndTail.Tail) && tailHead == Volatile.Read(ref tail->HeadAndTail.Head) && tailTail == Volatile.Read(ref tail->HeadAndTail.Tail)) + { + var count = GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); + for (var s = (NativeConcurrentQueueSegmentNotArm64*)head->NextSegment; s != tail; s = (NativeConcurrentQueueSegmentNotArm64*)s->NextSegment) + count += s->HeadAndTail.Tail - NativeConcurrentQueueSegmentNotArm64.FREEZE_OFFSET; + return count; + } + } + } + finally + { + _crossSegmentLock.Exit(); + } + } + + if ((spinCount >= 10 && (spinCount - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = spinCount >= 10 ? (spinCount - 10) / 2 : spinCount; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (spinCount <= 30 && 1 << spinCount < iterations) + iterations = 1 << spinCount; + Thread.SpinWait(iterations); + } + + spinCount = spinCount == int.MaxValue ? 10 : spinCount + 1; + } + } + } + + /// + /// Structure + /// + /// Segment pool + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(NativeMemoryPool segmentPool) + { + _crossSegmentLock = new NativeMonitorLock(new object()); + _segmentPool = segmentPool; + var segment = (NativeConcurrentQueueSegmentNotArm64*)_segmentPool.Rent(); + var array = (byte*)segment + sizeof(NativeConcurrentQueueSegmentNotArm64); + segment->Initialize((NativeConcurrentQueueSegmentNotArm64.Slot*)array); + _tail = _head = segment; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + _crossSegmentLock.Dispose(); + _segmentPool.Dispose(); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _crossSegmentLock.Enter(); + try + { + _tail->EnsureFrozenForEnqueues(); + var node = _head; + while (node != null) + { + var temp = node; + node = (NativeConcurrentQueueSegmentNotArm64*)node->NextSegment; + _segmentPool.Return(temp); + } + + var segment = (NativeConcurrentQueueSegmentNotArm64*)_segmentPool.Rent(); + var array = (byte*)segment + sizeof(NativeConcurrentQueueSegmentNotArm64); + segment->Initialize((NativeConcurrentQueueSegmentNotArm64.Slot*)array); + _tail = _head = segment; + } + finally + { + _crossSegmentLock.Exit(); + } + } + + /// + /// Enqueue + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enqueue(in T item) + { + if (!_tail->TryEnqueue(item)) + { + while (true) + { + var tail = _tail; + if (tail->TryEnqueue(item)) + return; + _crossSegmentLock.Enter(); + try + { + if (tail == _tail) + { + tail->EnsureFrozenForEnqueues(); + var newTail = (NativeConcurrentQueueSegmentNotArm64*)_segmentPool.Rent(); + var array = (byte*)newTail + sizeof(NativeConcurrentQueueSegmentNotArm64); + newTail->Initialize((NativeConcurrentQueueSegmentNotArm64.Slot*)array); + tail->NextSegment = (nint)newTail; + _tail = newTail; + } + } + finally + { + _crossSegmentLock.Exit(); + } + } + } + } + + /// + /// Try dequeue + /// + /// Item + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out T result) + { + var head = _head; + if (head->TryDequeue(out result)) + return true; + if (head->NextSegment == IntPtr.Zero) + { + result = default; + return false; + } + + while (true) + { + head = _head; + if (head->TryDequeue(out result)) + return true; + if (head->NextSegment == IntPtr.Zero) + { + result = default; + return false; + } + + if (head->TryDequeue(out result)) + return true; + _crossSegmentLock.Enter(); + try + { + if (head == _head) + { + _head = (NativeConcurrentQueueSegmentNotArm64*)head->NextSegment; + _segmentPool.Return(head); + } + } + finally + { + _crossSegmentLock.Exit(); + } + } + } + + /// + /// Get count + /// + /// Segment + /// Head + /// Tail + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetCount(NativeConcurrentQueueSegmentNotArm64* segment, int head, int tail) + { + if (head != tail && head != tail - NativeConcurrentQueueSegmentNotArm64.FREEZE_OFFSET) + { + head &= NativeConcurrentQueueSegmentNotArm64.SLOTS_MASK; + tail &= NativeConcurrentQueueSegmentNotArm64.SLOTS_MASK; + return head < tail ? tail - head : NativeConcurrentQueueSegmentNotArm64.LENGTH - head + tail; + } + + return 0; + } + + /// + /// Get count + /// + /// Head + /// Head head + /// Tail + /// Tail tail + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static long GetCount(NativeConcurrentQueueSegmentNotArm64* head, int headHead, NativeConcurrentQueueSegmentNotArm64* tail, int tailTail) + { + long count = 0; + var headTail = (head == tail ? tailTail : Volatile.Read(ref head->HeadAndTail.Tail)) - NativeConcurrentQueueSegmentNotArm64.FREEZE_OFFSET; + if (headHead < headTail) + { + headHead &= NativeConcurrentQueueSegmentNotArm64.SLOTS_MASK; + headTail &= NativeConcurrentQueueSegmentNotArm64.SLOTS_MASK; + count += headHead < headTail ? headTail - headHead : NativeConcurrentQueueSegmentNotArm64.LENGTH - headHead + headTail; + } + + if (head != tail) + { + for (var s = (NativeConcurrentQueueSegmentNotArm64*)head->NextSegment; s != tail; s = (NativeConcurrentQueueSegmentNotArm64*)s->NextSegment) + count += s->HeadAndTail.Tail - NativeConcurrentQueueSegmentNotArm64.FREEZE_OFFSET; + count += tailTail - NativeConcurrentQueueSegmentNotArm64.FREEZE_OFFSET; + } + + return count; + } + } + + /// + /// Native concurrentQueue segment + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct NativeConcurrentQueueSegmentNotArm64 where T : unmanaged + { + /// + /// Slots + /// + public Slot* Slots; + + /// + /// Length + /// + public const int LENGTH = 1024; + + /// + /// Slots mask + /// + public const int SLOTS_MASK = LENGTH - 1; + + /// + /// Head and tail + /// + public NativeConcurrentQueuePaddedHeadAndTailNotArm64 HeadAndTail; + + /// + /// Frozen for enqueues + /// + public bool FrozenForEnqueues; + + /// + /// Next segment + /// + public nint NextSegment; + + /// + /// Initialize + /// + /// Slots + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(Slot* slots) + { + Slots = slots; + for (var i = 0; i < LENGTH; ++i) + Slots[i].SequenceNumber = i; + HeadAndTail = new NativeConcurrentQueuePaddedHeadAndTailNotArm64(); + FrozenForEnqueues = false; + NextSegment = IntPtr.Zero; + } + + /// + /// Freeze offset + /// + public const int FREEZE_OFFSET = LENGTH * 2; + + /// + /// Ensure frozen for enqueues + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void EnsureFrozenForEnqueues() + { + if (!FrozenForEnqueues) + { + FrozenForEnqueues = true; + Interlocked.Add(ref HeadAndTail.Tail, FREEZE_OFFSET); + } + } + + /// + /// Try dequeue + /// + /// Item + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out T result) + { + var slots = Slots; + var count = 0; + while (true) + { + var currentHead = Volatile.Read(ref HeadAndTail.Head); + var slotsIndex = currentHead & SLOTS_MASK; + var sequenceNumber = Volatile.Read(ref slots[slotsIndex].SequenceNumber); + var diff = sequenceNumber - (currentHead + 1); + if (diff == 0) + { + if (Interlocked.CompareExchange(ref HeadAndTail.Head, currentHead + 1, currentHead) == currentHead) + { + result = slots[slotsIndex].Item; + Volatile.Write(ref slots[slotsIndex].SequenceNumber, currentHead + LENGTH); + return true; + } + } + else if (diff < 0) + { + var frozen = FrozenForEnqueues; + var currentTail = Volatile.Read(ref HeadAndTail.Tail); + if (currentTail - currentHead <= 0 || (frozen && currentTail - FREEZE_OFFSET - currentHead <= 0)) + { + result = default; + return false; + } + + if ((count >= 10 && (count - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + } + } + } + + /// + /// Try peek + /// + /// Peeked + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPeek() + { + var slots = Slots; + var count = 0; + while (true) + { + var currentHead = Volatile.Read(ref HeadAndTail.Head); + var slotsIndex = currentHead & SLOTS_MASK; + var sequenceNumber = Volatile.Read(ref slots[slotsIndex].SequenceNumber); + var diff = sequenceNumber - (currentHead + 1); + if (diff == 0) + return true; + if (diff < 0) + { + var frozen = FrozenForEnqueues; + var currentTail = Volatile.Read(ref HeadAndTail.Tail); + if (currentTail - currentHead <= 0 || (frozen && currentTail - FREEZE_OFFSET - currentHead <= 0)) + return false; + if ((count >= 10 && (count - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + } + } + } + + /// + /// Try enqueue + /// + /// Item + /// Enqueued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnqueue(in T item) + { + var slots = Slots; + while (true) + { + var currentTail = Volatile.Read(ref HeadAndTail.Tail); + var slotsIndex = currentTail & SLOTS_MASK; + var sequenceNumber = Volatile.Read(ref slots[slotsIndex].SequenceNumber); + var diff = sequenceNumber - currentTail; + if (diff == 0) + { + if (Interlocked.CompareExchange(ref HeadAndTail.Tail, currentTail + 1, currentTail) == currentTail) + { + slots[slotsIndex].Item = item; + Volatile.Write(ref slots[slotsIndex].SequenceNumber, currentTail + 1); + return true; + } + } + else if (diff < 0) + { + return false; + } + } + } + + /// + /// Slot + /// + [StructLayout(LayoutKind.Sequential)] + public struct Slot + { + /// + /// Item + /// + public T Item; + + /// + /// Sequence number + /// + public int SequenceNumber; + } + } + + /// + /// NativeConcurrentQueue padded head and tail + /// + [StructLayout(LayoutKind.Explicit, Size = 3 * CACHE_LINE_SIZE)] + internal struct NativeConcurrentQueuePaddedHeadAndTailNotArm64 + { + /// + /// Head + /// + [FieldOffset(1 * CACHE_LINE_SIZE)] public int Head; + + /// + /// Tail + /// + [FieldOffset(2 * CACHE_LINE_SIZE)] public int Tail; + + /// + /// Catch line size + /// + public const int CACHE_LINE_SIZE = 64; + } + + /// + /// Native concurrentQueue + /// (Slower than ConcurrentQueue, disable Enumerator, try peek either) + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct NativeConcurrentQueueArm64 : IDisposable where T : unmanaged + { + /// + /// Cross segment lock + /// + private NativeMonitorLock _crossSegmentLock; + + /// + /// Segment pool + /// + private NativeMemoryPool _segmentPool; + + /// + /// Tail + /// + private volatile NativeConcurrentQueueSegmentArm64* _tail; + + /// + /// Head + /// + private volatile NativeConcurrentQueueSegmentArm64* _head; + + /// + /// IsEmpty + /// + public bool IsEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var segment = _head; + while (true) + { + var next = Volatile.Read(ref segment->NextSegment); + if (segment->TryPeek()) + return false; + if (next != IntPtr.Zero) + segment = (NativeConcurrentQueueSegmentArm64*)next; + else if (Volatile.Read(ref segment->NextSegment) == IntPtr.Zero) + break; + } + + return true; + } + } + + /// + /// Count + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var spinCount = 0; + while (true) + { + var head = _head; + var tail = _tail; + var headHead = Volatile.Read(ref head->HeadAndTail.Head); + var headTail = Volatile.Read(ref head->HeadAndTail.Tail); + if (head == tail) + { + if (head == _head && tail == _tail && headHead == Volatile.Read(ref head->HeadAndTail.Head) && headTail == Volatile.Read(ref head->HeadAndTail.Tail)) + return GetCount(head, headHead, headTail); + } + else if ((NativeConcurrentQueueSegmentArm64*)head->NextSegment == tail) + { + var tailHead = Volatile.Read(ref tail->HeadAndTail.Head); + var tailTail = Volatile.Read(ref tail->HeadAndTail.Tail); + if (head == _head && tail == _tail && headHead == Volatile.Read(ref head->HeadAndTail.Head) && headTail == Volatile.Read(ref head->HeadAndTail.Tail) && tailHead == Volatile.Read(ref tail->HeadAndTail.Head) && tailTail == Volatile.Read(ref tail->HeadAndTail.Tail)) + return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); + } + else + { + _crossSegmentLock.Enter(); + try + { + if (head == _head && tail == _tail) + { + var tailHead = Volatile.Read(ref tail->HeadAndTail.Head); + var tailTail = Volatile.Read(ref tail->HeadAndTail.Tail); + if (headHead == Volatile.Read(ref head->HeadAndTail.Head) && headTail == Volatile.Read(ref head->HeadAndTail.Tail) && tailHead == Volatile.Read(ref tail->HeadAndTail.Head) && tailTail == Volatile.Read(ref tail->HeadAndTail.Tail)) + { + var count = GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail); + for (var s = (NativeConcurrentQueueSegmentArm64*)head->NextSegment; s != tail; s = (NativeConcurrentQueueSegmentArm64*)s->NextSegment) + count += s->HeadAndTail.Tail - NativeConcurrentQueueSegmentArm64.FREEZE_OFFSET; + return count; + } + } + } + finally + { + _crossSegmentLock.Exit(); + } + } + + if ((spinCount >= 10 && (spinCount - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = spinCount >= 10 ? (spinCount - 10) / 2 : spinCount; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (spinCount <= 30 && 1 << spinCount < iterations) + iterations = 1 << spinCount; + Thread.SpinWait(iterations); + } + + spinCount = spinCount == int.MaxValue ? 10 : spinCount + 1; + } + } + } + + /// + /// Structure + /// + /// Segment pool + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(NativeMemoryPool segmentPool) + { + _crossSegmentLock = new NativeMonitorLock(new object()); + _segmentPool = segmentPool; + var segment = (NativeConcurrentQueueSegmentArm64*)_segmentPool.Rent(); + var array = (byte*)segment + sizeof(NativeConcurrentQueueSegmentArm64); + segment->Initialize((NativeConcurrentQueueSegmentArm64.Slot*)array); + _tail = _head = segment; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + _crossSegmentLock.Dispose(); + _segmentPool.Dispose(); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _crossSegmentLock.Enter(); + try + { + _tail->EnsureFrozenForEnqueues(); + var node = _head; + while (node != null) + { + var temp = node; + node = (NativeConcurrentQueueSegmentArm64*)node->NextSegment; + _segmentPool.Return(temp); + } + + var segment = (NativeConcurrentQueueSegmentArm64*)_segmentPool.Rent(); + var array = (byte*)segment + sizeof(NativeConcurrentQueueSegmentArm64); + segment->Initialize((NativeConcurrentQueueSegmentArm64.Slot*)array); + _tail = _head = segment; + } + finally + { + _crossSegmentLock.Exit(); + } + } + + /// + /// Enqueue + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enqueue(in T item) + { + if (!_tail->TryEnqueue(item)) + { + while (true) + { + var tail = _tail; + if (tail->TryEnqueue(item)) + return; + _crossSegmentLock.Enter(); + try + { + if (tail == _tail) + { + tail->EnsureFrozenForEnqueues(); + var newTail = (NativeConcurrentQueueSegmentArm64*)_segmentPool.Rent(); + var array = (byte*)newTail + sizeof(NativeConcurrentQueueSegmentArm64); + newTail->Initialize((NativeConcurrentQueueSegmentArm64.Slot*)array); + tail->NextSegment = (nint)newTail; + _tail = newTail; + } + } + finally + { + _crossSegmentLock.Exit(); + } + } + } + } + + /// + /// Try dequeue + /// + /// Item + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out T result) + { + var head = _head; + if (head->TryDequeue(out result)) + return true; + if (head->NextSegment == IntPtr.Zero) + { + result = default; + return false; + } + + while (true) + { + head = _head; + if (head->TryDequeue(out result)) + return true; + if (head->NextSegment == IntPtr.Zero) + { + result = default; + return false; + } + + if (head->TryDequeue(out result)) + return true; + _crossSegmentLock.Enter(); + try + { + if (head == _head) + { + _head = (NativeConcurrentQueueSegmentArm64*)head->NextSegment; + _segmentPool.Return(head); + } + } + finally + { + _crossSegmentLock.Exit(); + } + } + } + + /// + /// Get count + /// + /// Segment + /// Head + /// Tail + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetCount(NativeConcurrentQueueSegmentArm64* segment, int head, int tail) + { + if (head != tail && head != tail - NativeConcurrentQueueSegmentArm64.FREEZE_OFFSET) + { + head &= NativeConcurrentQueueSegmentArm64.SLOTS_MASK; + tail &= NativeConcurrentQueueSegmentArm64.SLOTS_MASK; + return head < tail ? tail - head : NativeConcurrentQueueSegmentArm64.LENGTH - head + tail; + } + + return 0; + } + + /// + /// Get count + /// + /// Head + /// Head head + /// Tail + /// Tail tail + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static long GetCount(NativeConcurrentQueueSegmentArm64* head, int headHead, NativeConcurrentQueueSegmentArm64* tail, int tailTail) + { + long count = 0; + var headTail = (head == tail ? tailTail : Volatile.Read(ref head->HeadAndTail.Tail)) - NativeConcurrentQueueSegmentArm64.FREEZE_OFFSET; + if (headHead < headTail) + { + headHead &= NativeConcurrentQueueSegmentArm64.SLOTS_MASK; + headTail &= NativeConcurrentQueueSegmentArm64.SLOTS_MASK; + count += headHead < headTail ? headTail - headHead : NativeConcurrentQueueSegmentArm64.LENGTH - headHead + headTail; + } + + if (head != tail) + { + for (var s = (NativeConcurrentQueueSegmentArm64*)head->NextSegment; s != tail; s = (NativeConcurrentQueueSegmentArm64*)s->NextSegment) + count += s->HeadAndTail.Tail - NativeConcurrentQueueSegmentArm64.FREEZE_OFFSET; + count += tailTail - NativeConcurrentQueueSegmentArm64.FREEZE_OFFSET; + } + + return count; + } + } + + /// + /// Native concurrentQueue segment + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct NativeConcurrentQueueSegmentArm64 where T : unmanaged + { + /// + /// Slots + /// + public Slot* Slots; + + /// + /// Length + /// + public const int LENGTH = 1024; + + /// + /// Slots mask + /// + public const int SLOTS_MASK = LENGTH - 1; + + /// + /// Head and tail + /// + public NativeConcurrentQueuePaddedHeadAndTailArm64 HeadAndTail; + + /// + /// Frozen for enqueues + /// + public bool FrozenForEnqueues; + + /// + /// Next segment + /// + public nint NextSegment; + + /// + /// Initialize + /// + /// Slots + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Initialize(Slot* slots) + { + Slots = slots; + for (var i = 0; i < LENGTH; ++i) + Slots[i].SequenceNumber = i; + HeadAndTail = new NativeConcurrentQueuePaddedHeadAndTailArm64(); + FrozenForEnqueues = false; + NextSegment = IntPtr.Zero; + } + + /// + /// Freeze offset + /// + public const int FREEZE_OFFSET = LENGTH * 2; + + /// + /// Ensure frozen for enqueues + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void EnsureFrozenForEnqueues() + { + if (!FrozenForEnqueues) + { + FrozenForEnqueues = true; + Interlocked.Add(ref HeadAndTail.Tail, FREEZE_OFFSET); + } + } + + /// + /// Try dequeue + /// + /// Item + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out T result) + { + var slots = Slots; + var count = 0; + while (true) + { + var currentHead = Volatile.Read(ref HeadAndTail.Head); + var slotsIndex = currentHead & SLOTS_MASK; + var sequenceNumber = Volatile.Read(ref slots[slotsIndex].SequenceNumber); + var diff = sequenceNumber - (currentHead + 1); + if (diff == 0) + { + if (Interlocked.CompareExchange(ref HeadAndTail.Head, currentHead + 1, currentHead) == currentHead) + { + result = slots[slotsIndex].Item; + Volatile.Write(ref slots[slotsIndex].SequenceNumber, currentHead + LENGTH); + return true; + } + } + else if (diff < 0) + { + var frozen = FrozenForEnqueues; + var currentTail = Volatile.Read(ref HeadAndTail.Tail); + if (currentTail - currentHead <= 0 || (frozen && currentTail - FREEZE_OFFSET - currentHead <= 0)) + { + result = default; + return false; + } + + if ((count >= 10 && (count - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + } + } + } + + /// + /// Try peek + /// + /// Peeked + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPeek() + { + var slots = Slots; + var count = 0; + while (true) + { + var currentHead = Volatile.Read(ref HeadAndTail.Head); + var slotsIndex = currentHead & SLOTS_MASK; + var sequenceNumber = Volatile.Read(ref slots[slotsIndex].SequenceNumber); + var diff = sequenceNumber - (currentHead + 1); + if (diff == 0) + return true; + if (diff < 0) + { + var frozen = FrozenForEnqueues; + var currentTail = Volatile.Read(ref HeadAndTail.Tail); + if (currentTail - currentHead <= 0 || (frozen && currentTail - FREEZE_OFFSET - currentHead <= 0)) + return false; + if ((count >= 10 && (count - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + } + } + } + + /// + /// Try enqueue + /// + /// Item + /// Enqueued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnqueue(in T item) + { + var slots = Slots; + while (true) + { + var currentTail = Volatile.Read(ref HeadAndTail.Tail); + var slotsIndex = currentTail & SLOTS_MASK; + var sequenceNumber = Volatile.Read(ref slots[slotsIndex].SequenceNumber); + var diff = sequenceNumber - currentTail; + if (diff == 0) + { + if (Interlocked.CompareExchange(ref HeadAndTail.Tail, currentTail + 1, currentTail) == currentTail) + { + slots[slotsIndex].Item = item; + Volatile.Write(ref slots[slotsIndex].SequenceNumber, currentTail + 1); + return true; + } + } + else if (diff < 0) + { + return false; + } + } + } + + /// + /// Slot + /// + [StructLayout(LayoutKind.Sequential)] + public struct Slot + { + /// + /// Item + /// + public T Item; + + /// + /// Sequence number + /// + public int SequenceNumber; + } + } + + /// + /// NativeConcurrentQueue padded head and tail + /// + [StructLayout(LayoutKind.Explicit, Size = 3 * CACHE_LINE_SIZE)] + internal struct NativeConcurrentQueuePaddedHeadAndTailArm64 + { + /// + /// Head + /// + [FieldOffset(1 * CACHE_LINE_SIZE)] public int Head; + + /// + /// Tail + /// + [FieldOffset(2 * CACHE_LINE_SIZE)] public int Tail; + + /// + /// Catch line size + /// + public const int CACHE_LINE_SIZE = 128; + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentQueue.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentQueue.cs.meta new file mode 100644 index 00000000..a06a5ca0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e4c721bccdf648baad2f6e70fe8b32a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentSpinLock.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentSpinLock.cs new file mode 100644 index 00000000..a42b93dd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentSpinLock.cs @@ -0,0 +1,180 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native concurrent spinLock + /// + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeConcurrentSpinLock : IDisposable, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeConcurrentSpinLockHandle + { + /// + /// Sequence number + /// + public int SequenceNumber; + + /// + /// Next sequence number + /// + public int NextSequenceNumber; + + /// + /// Sleep threshold + /// + public int SleepThreshold; + } + + /// + /// Handle + /// + private readonly NativeConcurrentSpinLockHandle* _handle; + + /// + /// Structure + /// + /// Sleep threshold + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeConcurrentSpinLock(int sleepThreshold) + { + if (sleepThreshold < -1) + sleepThreshold = -1; + else if (sleepThreshold >= 0 && sleepThreshold < 10) + sleepThreshold = 10; + _handle = (NativeConcurrentSpinLockHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeConcurrentSpinLockHandle)); + _handle->SequenceNumber = 0; + _handle->NextSequenceNumber = 1; + _handle->SleepThreshold = sleepThreshold; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Sleep threshold + /// + public int SleepThreshold => _handle->SleepThreshold; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeConcurrentSpinLock other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeConcurrentSpinLock nativeConcurrentSpinLock && nativeConcurrentSpinLock == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => "NativeConcurrentSpinLock"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeConcurrentSpinLock left, NativeConcurrentSpinLock right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeConcurrentSpinLock left, NativeConcurrentSpinLock right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enter() + { + var sequenceNumber = Interlocked.Add(ref _handle->SequenceNumber, 1); + if (sequenceNumber != _handle->NextSequenceNumber) + { + var count = 0; + var sleepThreshold = _handle->SleepThreshold; + do + { + if ((count >= 10 && ((count >= sleepThreshold && sleepThreshold >= 0) || (count - 10) % 2 == 0)) || Environment.ProcessorCount == 1) + { + if (count >= sleepThreshold && sleepThreshold >= 0) + { + Thread.Sleep(1); + } + else + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + } while (sequenceNumber != _handle->NextSequenceNumber); + } + } + + /// + /// Exit + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Exit() => Interlocked.Add(ref _handle->NextSequenceNumber, 1); + + /// + /// Empty + /// + public static NativeConcurrentSpinLock Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentSpinLock.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentSpinLock.cs.meta new file mode 100644 index 00000000..86c97f79 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentSpinLock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a76d3296d0fe4349b1247bf3b0050a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentStack.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentStack.cs new file mode 100644 index 00000000..8f981778 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentStack.cs @@ -0,0 +1,338 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if !NET6_0_OR_GREATER +using System.Security.Cryptography; +#endif + +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native concurrentStack + /// (Slower than ConcurrentStack, disable Enumerator, try peek, push/pop range either) + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeConcurrentStack : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeConcurrentStackHandle + { + /// + /// Head + /// + public volatile nint Head; + + /// + /// Node pool + /// + public NativeMemoryPool NodePool; + + /// + /// Node pool lock + /// + public NativeConcurrentSpinLock NodePoolLock; + } + + /// + /// Handle + /// + private readonly NativeConcurrentStackHandle* _handle; + + /// + /// Structure + /// + /// Size + /// Max free slabs + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeConcurrentStack(int size, int maxFreeSlabs) + { + var nodePool = new NativeMemoryPool(size, sizeof(Node), maxFreeSlabs); + _handle = (NativeConcurrentStackHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeConcurrentStackHandle)); + _handle->Head = IntPtr.Zero; + _handle->NodePool = nodePool; + _handle->NodePoolLock = new NativeConcurrentSpinLock(-1); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// IsEmpty + /// + public bool IsEmpty => _handle->Head == IntPtr.Zero; + + /// + /// Count + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var count = 0; + for (var node = (Node*)_handle->Head; node != null; node = node->Next) + count++; + return count; + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeConcurrentStack other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeConcurrentStack nativeConcurrentStack && nativeConcurrentStack == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeConcurrentStack<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeConcurrentStack left, NativeConcurrentStack right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeConcurrentStack left, NativeConcurrentStack right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + _handle->NodePool.Dispose(); + _handle->NodePoolLock.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _handle->NodePoolLock.Enter(); + try + { + var node = (Node*)_handle->Head; + while (node != null) + { + var temp = node; + node = node->Next; + _handle->NodePool.Return(temp); + } + } + finally + { + _handle->NodePoolLock.Exit(); + } + } + + /// + /// Push + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Push(in T item) + { + Node* newNode; + _handle->NodePoolLock.Enter(); + try + { + newNode = (Node*)_handle->NodePool.Rent(); + } + finally + { + _handle->NodePoolLock.Exit(); + } + + newNode->Value = item; + newNode->Next = (Node*)_handle->Head; + if (Interlocked.CompareExchange(ref _handle->Head, (nint)newNode, (nint)newNode->Next) == (nint)newNode->Next) + return; + var count = 0; + do + { + if ((count >= 10 && (count - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + newNode->Next = (Node*)_handle->Head; + } while (Interlocked.CompareExchange(ref _handle->Head, (nint)newNode, (nint)newNode->Next) != (nint)newNode->Next); + } + + /// + /// Try pop + /// + /// Item + /// Popped + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPop(out T result) + { + var head = (Node*)_handle->Head; + if (head == null) + { + result = default; + return false; + } + + if (Interlocked.CompareExchange(ref _handle->Head, (nint)head->Next, (nint)head) == (nint)head) + { + result = head->Value; + _handle->NodePoolLock.Enter(); + try + { + _handle->NodePool.Return(head); + } + finally + { + _handle->NodePoolLock.Exit(); + } + + return true; + } + + var count = 0; + var backoff = 1; +#if !NET6_0_OR_GREATER + Span random = stackalloc byte[1]; +#endif + while (true) + { + head = (Node*)_handle->Head; + if (head == null) + { + result = default; + return false; + } + + if (Interlocked.CompareExchange(ref _handle->Head, (nint)head->Next, (nint)head) == (nint)head) + { + result = head->Value; + _handle->NodePoolLock.Enter(); + try + { + _handle->NodePool.Return(head); + } + finally + { + _handle->NodePoolLock.Exit(); + } + + return true; + } + + for (var i = 0; i < backoff; ++i) + { + if ((count >= 10 && (count - 10) % 2 == 0) || Environment.ProcessorCount == 1) + { + var yieldsSoFar = count >= 10 ? (count - 10) / 2 : count; + if (yieldsSoFar % 5 == 4) + Thread.Sleep(0); + else + Thread.Yield(); + } + else + { + var iterations = Environment.ProcessorCount / 2; + if (count <= 30 && 1 << count < iterations) + iterations = 1 << count; + Thread.SpinWait(iterations); + } + + count = count == int.MaxValue ? 10 : count + 1; + } + + if (count >= 10 || Environment.ProcessorCount == 1) + { +#if NET6_0_OR_GREATER + backoff = Random.Shared.Next(1, 8); +#else + RandomNumberGenerator.Fill(random); + backoff = random[0] % 7 + 1; +#endif + } + else + { + backoff *= 2; + } + } + } + + /// + /// Empty + /// + public static NativeConcurrentStack Empty => new(); + + /// + /// Node + /// + [StructLayout(LayoutKind.Sequential)] + private struct Node + { + /// + /// Value + /// + public T Value; + + /// + /// Next + /// + public Node* Next; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentStack.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentStack.cs.meta new file mode 100644 index 00000000..cad9f464 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeConcurrentStack.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb99d22c8b973459292145f9fb620e54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeDictionary.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeDictionary.cs new file mode 100644 index 00000000..173a9fb2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeDictionary.cs @@ -0,0 +1,971 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Collections.Generic; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native dictionary + /// + /// Type + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeDictionary : IDisposable, IEquatable> where TKey : unmanaged, IEquatable where TValue : unmanaged + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeDictionaryHandle + { + /// + /// Buckets + /// + public int* Buckets; + + /// + /// Entries + /// + public Entry* Entries; + + /// + /// BucketsLength + /// + public int BucketsLength; + + /// + /// EntriesLength + /// + public int EntriesLength; + + /// + /// FastModMultiplier + /// + public ulong FastModMultiplier; + + /// + /// Count + /// + public int Count; + + /// + /// FreeList + /// + public int FreeList; + + /// + /// FreeCount + /// + public int FreeCount; + + /// + /// Version + /// + public int Version; + + /// + /// Keys + /// + public KeyCollection Keys; + + /// + /// Values + /// + public ValueCollection Values; + } + + /// + /// Handle + /// + private readonly NativeDictionaryHandle* _handle; + + /// + /// Keys + /// + public KeyCollection Keys => _handle->Keys; + + /// + /// Values + /// + public ValueCollection Values => _handle->Values; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeDictionary(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeDictionaryHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeDictionaryHandle)); + _handle->Count = 0; + _handle->FreeCount = 0; + _handle->Version = 0; + Initialize(capacity); + _handle->Keys = new KeyCollection(this); + _handle->Values = new ValueCollection(this); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Count - _handle->FreeCount == 0; + + /// + /// Get or set value + /// + /// Key + public TValue this[in TKey key] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ref var value = ref FindValue(key); + if (Unsafe.AsPointer(ref Unsafe.AsRef(in value)) != null) + return value; + throw new KeyNotFoundException(key.ToString()); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => TryInsertOverwriteExisting(key, value); + } + + /// + /// Count + /// + public int Count => _handle->Count - _handle->FreeCount; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeDictionary other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeDictionary nativeDictionary && nativeDictionary == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeDictionary<{typeof(TKey).Name}, {typeof(TValue).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeDictionary left, NativeDictionary right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeDictionary left, NativeDictionary right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Buckets); + NativeMemoryAllocator.Free(_handle->Entries); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + var count = _handle->Count; + if (count > 0) + { + Unsafe.InitBlockUnaligned(_handle->Buckets, 0, (uint)(count * sizeof(int))); + _handle->Count = 0; + _handle->FreeList = -1; + _handle->FreeCount = 0; + Unsafe.InitBlockUnaligned(_handle->Entries, 0, (uint)(count * sizeof(Entry))); + } + } + + /// + /// Add + /// + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(in TKey key, in TValue value) => TryInsertThrowOnExisting(key, value); + + /// + /// Try add + /// + /// Key + /// Value + /// Added + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryAdd(in TKey key, in TValue value) => TryInsertNone(key, value); + + /// + /// Remove + /// + /// Key + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in TKey key) + { + uint collisionCount = 0; + var hashCode = (uint)key.GetHashCode(); + ref var bucket = ref GetBucket(hashCode); + var last = -1; + var i = bucket - 1; + while (i >= 0) + { + ref var entry = ref _handle->Entries[i]; + if (entry.HashCode == hashCode && entry.Key.Equals(key)) + { + if (last < 0) + bucket = entry.Next + 1; + else + _handle->Entries[last].Next = entry.Next; + entry.Next = -3 - _handle->FreeList; + _handle->FreeList = i; + _handle->FreeCount++; + return true; + } + + last = i; + i = entry.Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + return false; + } + + /// + /// Remove + /// + /// Key + /// Value + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in TKey key, out TValue value) + { + uint collisionCount = 0; + var hashCode = (uint)key.GetHashCode(); + ref var bucket = ref GetBucket(hashCode); + var last = -1; + var i = bucket - 1; + while (i >= 0) + { + ref var entry = ref _handle->Entries[i]; + if (entry.HashCode == hashCode && entry.Key.Equals(key)) + { + if (last < 0) + bucket = entry.Next + 1; + else + _handle->Entries[last].Next = entry.Next; + value = entry.Value; + entry.Next = -3 - _handle->FreeList; + _handle->FreeList = i; + _handle->FreeCount++; + return true; + } + + last = i; + i = entry.Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + value = default; + return false; + } + + /// + /// Contains key + /// + /// Key + /// Contains key + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(in TKey key) => Unsafe.AsPointer(ref Unsafe.AsRef(in FindValue(key))) != null; + + /// + /// Try to get the value + /// + /// Key + /// Value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in TKey key, out TValue value) + { + ref var valRef = ref FindValue(key); + if (Unsafe.AsPointer(ref Unsafe.AsRef(in valRef)) != null) + { + value = valRef; + return true; + } + + value = default; + return false; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + var currentCapacity = _handle->EntriesLength; + if (currentCapacity >= capacity) + return currentCapacity; + _handle->Version++; + var newSize = HashHelpers.GetPrime(capacity); + Resize(newSize); + return newSize; + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess() => TrimExcess(Count); + + /// + /// Trim excess + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + var newSize = HashHelpers.GetPrime(capacity); + var oldEntries = _handle->Entries; + var currentCapacity = _handle->EntriesLength; + if (newSize >= currentCapacity) + return currentCapacity; + var oldCount = _handle->Count; + _handle->Version++; + NativeMemoryAllocator.Free(_handle->Buckets); + Initialize(newSize); + var newEntries = _handle->Entries; + var newCount = 0; + for (var i = 0; i < oldCount; ++i) + { + var hashCode = oldEntries[i].HashCode; + if (oldEntries[i].Next >= -1) + { + ref var entry = ref newEntries[newCount]; + entry = oldEntries[i]; + ref var bucket = ref GetBucket(hashCode); + entry.Next = bucket - 1; + bucket = newCount + 1; + newCount++; + } + } + + NativeMemoryAllocator.Free(oldEntries); + _handle->Count = newCount; + _handle->FreeCount = 0; + return newSize; + } + + /// + /// Find value + /// + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ref TValue FindValue(in TKey key) + { + var hashCode = (uint)key.GetHashCode(); + var i = GetBucket(hashCode); + uint collisionCount = 0; + i--; + do + { + if ((uint)i >= (uint)_handle->EntriesLength) + return ref Unsafe.AsRef(null); + ref var entry = ref _handle->Entries[i]; + if (entry.HashCode == hashCode && entry.Key.Equals(key)) + return ref entry.Value; + i = entry.Next; + collisionCount++; + } while (collisionCount <= (uint)_handle->EntriesLength); + + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + /// + /// Initialize + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Initialize(int capacity) + { + var size = HashHelpers.GetPrime(capacity); + _handle->FreeList = -1; + _handle->Buckets = (int*)NativeMemoryAllocator.AllocZeroed((uint)(size * sizeof(int))); + _handle->Entries = (Entry*)NativeMemoryAllocator.AllocZeroed((uint)(size * sizeof(Entry))); + _handle->BucketsLength = size; + _handle->EntriesLength = size; + _handle->FastModMultiplier = IntPtr.Size == 8 ? HashHelpers.GetFastModMultiplier((uint)size) : 0; + } + + /// + /// Resize + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Resize() => Resize(HashHelpers.ExpandPrime(_handle->Count)); + + /// + /// Resize + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Resize(int newSize) + { + var entries = (Entry*)NativeMemoryAllocator.AllocZeroed((uint)(newSize * sizeof(Entry))); + var count = _handle->Count; + Unsafe.CopyBlockUnaligned(entries, _handle->Entries, (uint)(count * sizeof(Entry))); + var buckets = (int*)NativeMemoryAllocator.AllocZeroed((uint)(newSize * sizeof(int))); + NativeMemoryAllocator.Free(_handle->Buckets); + _handle->Buckets = buckets; + _handle->BucketsLength = newSize; + _handle->FastModMultiplier = IntPtr.Size == 8 ? HashHelpers.GetFastModMultiplier((uint)newSize) : 0; + for (var i = 0; i < count; ++i) + { + if (entries[i].Next >= -1) + { + ref var bucket = ref GetBucket(entries[i].HashCode); + entries[i].Next = bucket - 1; + bucket = i + 1; + } + } + + NativeMemoryAllocator.Free(_handle->Entries); + _handle->Entries = entries; + _handle->EntriesLength = newSize; + } + + /// + /// Insert + /// + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void TryInsertOverwriteExisting(in TKey key, in TValue value) + { + var hashCode = (uint)key.GetHashCode(); + uint collisionCount = 0; + ref var bucket = ref GetBucket(hashCode); + var i = bucket - 1; + while (true) + { + if ((uint)i >= (uint)_handle->EntriesLength) + break; + if (_handle->Entries[i].HashCode == hashCode && _handle->Entries[i].Key.Equals(key)) + { + _handle->Entries[i].Value = value; + return; + } + + i = _handle->Entries[i].Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + int index; + if (_handle->FreeCount > 0) + { + index = _handle->FreeList; + _handle->FreeList = -3 - _handle->Entries[_handle->FreeList].Next; + _handle->FreeCount--; + } + else + { + var count = _handle->Count; + if (count == _handle->EntriesLength) + { + Resize(); + bucket = ref GetBucket(hashCode); + } + + index = count; + _handle->Count = count + 1; + } + + ref var entry = ref _handle->Entries[index]; + entry.HashCode = hashCode; + entry.Next = bucket - 1; + entry.Key = key; + entry.Value = value; + bucket = index + 1; + _handle->Version++; + } + + /// + /// Insert + /// + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool TryInsertThrowOnExisting(in TKey key, in TValue value) + { + var hashCode = (uint)key.GetHashCode(); + uint collisionCount = 0; + ref var bucket = ref GetBucket(hashCode); + var i = bucket - 1; + while (true) + { + if ((uint)i >= (uint)_handle->EntriesLength) + break; + if (_handle->Entries[i].HashCode == hashCode && _handle->Entries[i].Key.Equals(key)) + throw new ArgumentException($"Argument_AddingDuplicateWithKey, {key}"); + i = _handle->Entries[i].Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + int index; + if (_handle->FreeCount > 0) + { + index = _handle->FreeList; + _handle->FreeList = -3 - _handle->Entries[_handle->FreeList].Next; + _handle->FreeCount--; + } + else + { + var count = _handle->Count; + if (count == _handle->EntriesLength) + { + Resize(); + bucket = ref GetBucket(hashCode); + } + + index = count; + _handle->Count = count + 1; + } + + ref var entry = ref _handle->Entries[index]; + entry.HashCode = hashCode; + entry.Next = bucket - 1; + entry.Key = key; + entry.Value = value; + bucket = index + 1; + _handle->Version++; + return true; + } + + /// + /// Insert + /// + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool TryInsertNone(in TKey key, in TValue value) + { + var hashCode = (uint)key.GetHashCode(); + uint collisionCount = 0; + ref var bucket = ref GetBucket(hashCode); + var i = bucket - 1; + while (true) + { + if ((uint)i >= (uint)_handle->EntriesLength) + break; + if (_handle->Entries[i].HashCode == hashCode && _handle->Entries[i].Key.Equals(key)) + return false; + i = _handle->Entries[i].Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + int index; + if (_handle->FreeCount > 0) + { + index = _handle->FreeList; + _handle->FreeList = -3 - _handle->Entries[_handle->FreeList].Next; + _handle->FreeCount--; + } + else + { + var count = _handle->Count; + if (count == _handle->EntriesLength) + { + Resize(); + bucket = ref GetBucket(hashCode); + } + + index = count; + _handle->Count = count + 1; + } + + ref var entry = ref _handle->Entries[index]; + entry.HashCode = hashCode; + entry.Next = bucket - 1; + entry.Key = key; + entry.Value = value; + bucket = index + 1; + _handle->Version++; + return true; + } + + /// + /// Get bucket ref + /// + /// HashCode + /// Bucket ref + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ref int GetBucket(uint hashCode) => ref IntPtr.Size == 8 ? ref _handle->Buckets[HashHelpers.FastMod(hashCode, (uint)_handle->BucketsLength, _handle->FastModMultiplier)] : ref _handle->Buckets[hashCode % _handle->BucketsLength]; + + /// + /// Entry + /// + private struct Entry + { + /// + /// HashCode + /// + public uint HashCode; + + /// + /// Next + /// + public int Next; + + /// + /// Key + /// + public TKey Key; + + /// + /// Value + /// + public TValue Value; + } + + /// + /// Empty + /// + public static NativeDictionary Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeDictionary + /// + private readonly NativeDictionary _nativeDictionary; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Index + /// + private int _index; + + /// + /// Current + /// + private KeyValuePair _current; + + /// + /// Structure + /// + /// NativeDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeDictionary nativeDictionary) + { + _nativeDictionary = nativeDictionary; + _version = nativeDictionary._handle->Version; + _index = 0; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeDictionary._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + while ((uint)_index < (uint)_nativeDictionary._handle->Count) + { + ref var entry = ref _nativeDictionary._handle->Entries[_index++]; + if (entry.Next >= -1) + { + _current = new KeyValuePair(entry.Key, entry.Value); + return true; + } + } + + _index = _nativeDictionary._handle->Count + 1; + _current = default; + return false; + } + + /// + /// Current + /// + public KeyValuePair Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + + /// + /// Key collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct KeyCollection + { + /// + /// NativeDictionary + /// + private readonly NativeDictionary _nativeDictionary; + + /// + /// Structure + /// + /// NativeDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal KeyCollection(in NativeDictionary nativeDictionary) => _nativeDictionary = nativeDictionary; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeDictionary); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeDictionary + /// + private readonly NativeDictionary _nativeDictionary; + + /// + /// Index + /// + private int _index; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Current + /// + private TKey _currentKey; + + /// + /// Structure + /// + /// NativeDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeDictionary nativeDictionary) + { + _nativeDictionary = nativeDictionary; + _version = nativeDictionary._handle->Version; + _index = 0; + _currentKey = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeDictionary._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + while ((uint)_index < (uint)_nativeDictionary._handle->Count) + { + ref var entry = ref _nativeDictionary._handle->Entries[_index++]; + if (entry.Next >= -1) + { + _currentKey = entry.Key; + return true; + } + } + + _index = _nativeDictionary._handle->Count + 1; + _currentKey = default; + return false; + } + + /// + /// Current + /// + public TKey Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _currentKey; + } + } + } + + /// + /// Value collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct ValueCollection + { + /// + /// NativeDictionary + /// + private readonly NativeDictionary _nativeDictionary; + + /// + /// Structure + /// + /// NativeDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ValueCollection(in NativeDictionary nativeDictionary) => _nativeDictionary = nativeDictionary; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeDictionary); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeDictionary + /// + private readonly NativeDictionary _nativeDictionary; + + /// + /// Index + /// + private int _index; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Current + /// + private TValue _currentValue; + + /// + /// Structure + /// + /// NativeDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeDictionary nativeDictionary) + { + _nativeDictionary = nativeDictionary; + _version = nativeDictionary._handle->Version; + _index = 0; + _currentValue = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeDictionary._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + while ((uint)_index < (uint)_nativeDictionary._handle->Count) + { + ref var entry = ref _nativeDictionary._handle->Entries[_index++]; + if (entry.Next >= -1) + { + _currentValue = entry.Value; + return true; + } + } + + _index = _nativeDictionary._handle->Count + 1; + _currentValue = default; + return false; + } + + /// + /// Current + /// + public TValue Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _currentValue; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeDictionary.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeDictionary.cs.meta new file mode 100644 index 00000000..2764e578 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 413873e8f629844b9b9d4136907a4a72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeHashSet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeHashSet.cs new file mode 100644 index 00000000..c886df6e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeHashSet.cs @@ -0,0 +1,550 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native hashSet + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeHashSet : IDisposable, IEquatable> where T : unmanaged, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeHashSetHandle + { + /// + /// Buckets + /// + public int* Buckets; + + /// + /// Entries + /// + public Entry* Entries; + + /// + /// BucketsLength + /// + public int BucketsLength; + + /// + /// EntriesLength + /// + public int EntriesLength; + + /// + /// FastModMultiplier + /// + public ulong FastModMultiplier; + + /// + /// Count + /// + public int Count; + + /// + /// FreeList + /// + public int FreeList; + + /// + /// FreeCount + /// + public int FreeCount; + + /// + /// Version + /// + public int Version; + } + + /// + /// Handle + /// + private readonly NativeHashSetHandle* _handle; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeHashSet(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeHashSetHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeHashSetHandle)); + _handle->Count = 0; + _handle->FreeCount = 0; + _handle->Version = 0; + Initialize(capacity); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Count - _handle->FreeCount == 0; + + /// + /// Count + /// + public int Count => _handle->Count - _handle->FreeCount; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeHashSet other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeHashSet nativeHashSet && nativeHashSet == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeHashSet<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeHashSet left, NativeHashSet right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeHashSet left, NativeHashSet right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Buckets); + NativeMemoryAllocator.Free(_handle->Entries); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + var count = _handle->Count; + if (count > 0) + { + Unsafe.InitBlockUnaligned(_handle->Buckets, 0, (uint)(_handle->BucketsLength * sizeof(int))); + _handle->Count = 0; + _handle->FreeList = -1; + _handle->FreeCount = 0; + Unsafe.InitBlockUnaligned(_handle->Entries, 0, (uint)(count * sizeof(Entry))); + } + } + + /// + /// Add + /// + /// Item + /// Added + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Add(in T item) + { + uint collisionCount = 0; + var hashCode = item.GetHashCode(); + ref var bucket = ref GetBucketRef(hashCode); + var i = bucket - 1; + while (i >= 0) + { + ref var entry = ref _handle->Entries[i]; + if (entry.HashCode == hashCode && entry.Value.Equals(item)) + return false; + i = entry.Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + int index; + if (_handle->FreeCount > 0) + { + index = _handle->FreeList; + _handle->FreeCount--; + _handle->FreeList = -3 - _handle->Entries[_handle->FreeList].Next; + } + else + { + var count = _handle->Count; + if (count == _handle->EntriesLength) + { + Resize(); + bucket = ref GetBucketRef(hashCode); + } + + index = count; + _handle->Count = count + 1; + } + + ref var newEntry = ref _handle->Entries[index]; + newEntry.HashCode = hashCode; + newEntry.Next = bucket - 1; + newEntry.Value = item; + bucket = index + 1; + _handle->Version++; + return true; + } + + /// + /// Remove + /// + /// Item + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in T item) + { + uint collisionCount = 0; + var last = -1; + var hashCode = item.GetHashCode(); + ref var bucket = ref GetBucketRef(hashCode); + var i = bucket - 1; + while (i >= 0) + { + ref var entry = ref _handle->Entries[i]; + if (entry.HashCode == hashCode && entry.Value.Equals(item)) + { + if (last < 0) + bucket = entry.Next + 1; + else + _handle->Entries[last].Next = entry.Next; + entry.Next = -3 - _handle->FreeList; + _handle->FreeList = i; + _handle->FreeCount++; + return true; + } + + last = i; + i = entry.Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + return false; + } + + /// + /// Contains + /// + /// Item + /// Contains + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(in T item) => FindItemIndex(item) >= 0; + + /// + /// Try to get the actual value + /// + /// Equal value + /// Actual value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in T equalValue, out T actualValue) + { + var index = FindItemIndex(equalValue); + if (index >= 0) + { + actualValue = _handle->Entries[index].Value; + return true; + } + + actualValue = default; + return false; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + var currentCapacity = _handle->EntriesLength; + if (currentCapacity >= capacity) + return currentCapacity; + var newSize = HashHelpers.GetPrime(capacity); + Resize(newSize); + return newSize; + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess() + { + var capacity = _handle->Count - _handle->FreeCount; + var newSize = HashHelpers.GetPrime(capacity); + var oldEntries = _handle->Entries; + var currentCapacity = _handle->EntriesLength; + if (newSize >= currentCapacity) + return currentCapacity; + var oldCount = _handle->Count; + _handle->Version++; + NativeMemoryAllocator.Free(_handle->Buckets); + Initialize(newSize); + var newEntries = _handle->Entries; + var count = 0; + for (var i = 0; i < oldCount; ++i) + { + var hashCode = oldEntries[i].HashCode; + if (oldEntries[i].Next >= -1) + { + ref var entry = ref newEntries[count]; + entry = oldEntries[i]; + ref var bucket = ref GetBucketRef(hashCode); + entry.Next = bucket - 1; + bucket = count + 1; + count++; + } + } + + NativeMemoryAllocator.Free(oldEntries); + _handle->Count = capacity; + _handle->FreeCount = 0; + return newSize; + } + + /// + /// Initialize + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int Initialize(int capacity) + { + var size = HashHelpers.GetPrime(capacity); + _handle->FreeList = -1; + _handle->Buckets = (int*)NativeMemoryAllocator.AllocZeroed((uint)(size * sizeof(int))); + _handle->Entries = (Entry*)NativeMemoryAllocator.AllocZeroed((uint)(size * sizeof(Entry))); + _handle->BucketsLength = size; + _handle->EntriesLength = size; + _handle->FastModMultiplier = IntPtr.Size == 8 ? HashHelpers.GetFastModMultiplier((uint)size) : 0; + return size; + } + + /// + /// Resize + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Resize() => Resize(HashHelpers.ExpandPrime(_handle->Count)); + + /// + /// Resize + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Resize(int newSize) + { + var entries = (Entry*)NativeMemoryAllocator.AllocZeroed((uint)(newSize * sizeof(Entry))); + var count = _handle->Count; + Unsafe.CopyBlockUnaligned(entries, _handle->Entries, (uint)(_handle->EntriesLength * sizeof(Entry))); + var buckets = (int*)NativeMemoryAllocator.AllocZeroed((uint)(newSize * sizeof(int))); + NativeMemoryAllocator.Free(_handle->Buckets); + _handle->Buckets = buckets; + _handle->BucketsLength = newSize; + _handle->FastModMultiplier = IntPtr.Size == 8 ? HashHelpers.GetFastModMultiplier((uint)newSize) : 0; + for (var i = 0; i < count; ++i) + { + ref var entry = ref entries[i]; + if (entry.Next >= -1) + { + ref var bucket = ref GetBucketRef(entry.HashCode); + entry.Next = bucket - 1; + bucket = i + 1; + } + } + + NativeMemoryAllocator.Free(_handle->Entries); + _handle->Entries = entries; + _handle->EntriesLength = newSize; + } + + /// + /// Find item index + /// + /// Item + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int FindItemIndex(in T item) + { + uint collisionCount = 0; + var hashCode = item.GetHashCode(); + var i = GetBucketRef(hashCode) - 1; + while (i >= 0) + { + ref var entry = ref _handle->Entries[i]; + if (entry.HashCode == hashCode && entry.Value.Equals(item)) + return i; + i = entry.Next; + collisionCount++; + if (collisionCount > (uint)_handle->EntriesLength) + throw new InvalidOperationException("ConcurrentOperationsNotSupported"); + } + + return -1; + } + + /// + /// Get bucket ref + /// + /// HashCode + /// Bucket ref + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ref int GetBucketRef(int hashCode) => ref IntPtr.Size == 8 ? ref _handle->Buckets[HashHelpers.FastMod((uint)hashCode, (uint)_handle->BucketsLength, _handle->FastModMultiplier)] : ref _handle->Buckets[(uint)hashCode % (uint)_handle->BucketsLength]; + + /// + /// Entry + /// + private struct Entry + { + /// + /// HashCode + /// + public int HashCode; + + /// + /// Next + /// + public int Next; + + /// + /// Value + /// + public T Value; + } + + /// + /// Empty + /// + public static NativeHashSet Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeHashSet + /// + private readonly NativeHashSet _nativeHashSet; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Index + /// + private int _index; + + /// + /// Current + /// + private T _current; + + /// + /// Structure + /// + /// NativeHashSet + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeHashSet nativeHashSet) + { + _nativeHashSet = nativeHashSet; + _version = nativeHashSet._handle->Version; + _index = 0; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeHashSet._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + while ((uint)_index < (uint)_nativeHashSet._handle->Count) + { + ref var entry = ref _nativeHashSet._handle->Entries[_index++]; + if (entry.Next >= -1) + { + _current = entry.Value; + return true; + } + } + + _index = _nativeHashSet._handle->Count + 1; + _current = default; + return false; + } + + /// + /// Current + /// + public T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeHashSet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeHashSet.cs.meta new file mode 100644 index 00000000..3efb9027 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeHashSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d7a63489e1ec43c4a04d8c8832b7510 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeList.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeList.cs new file mode 100644 index 00000000..e96dc802 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeList.cs @@ -0,0 +1,676 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native list + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeList : IDisposable, IEquatable> where T : unmanaged, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeListHandle + { + /// + /// Array + /// + public T* Array; + + /// + /// Length + /// + public int Length; + + /// + /// Size + /// + public int Size; + + /// + /// Version + /// + public int Version; + } + + /// + /// Handle + /// + private readonly NativeListHandle* _handle; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeList(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeListHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeListHandle)); + _handle->Array = (T*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(T))); + _handle->Length = capacity; + _handle->Size = 0; + _handle->Version = 0; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Size == 0; + + /// + /// Get or set value + /// + /// Index + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Get or set value + /// + /// Index + public ref T this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Count + /// + public int Count => _handle->Size; + + /// + /// Capacity + /// + public int Capacity + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _handle->Length; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + if (value < _handle->Size) + throw new ArgumentOutOfRangeException(nameof(Capacity), value, "SmallCapacity"); + if (value != _handle->Length) + { + if (value > 0) + { + var newItems = (T*)NativeMemoryAllocator.Alloc((uint)(value * sizeof(T))); + if (_handle->Size > 0) + Unsafe.CopyBlockUnaligned(newItems, _handle->Array, (uint)(_handle->Size * sizeof(T))); + NativeMemoryAllocator.Free(_handle->Array); + _handle->Array = newItems; + _handle->Length = value; + } + else + { + NativeMemoryAllocator.Free(_handle->Array); + _handle->Array = (T*)NativeMemoryAllocator.Alloc(0); + _handle->Length = 0; + } + } + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeList other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeList nativeList && nativeList == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeList<{typeof(T).Name}>"; + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Span(NativeList nativeList) => nativeList.AsSpan(); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(NativeList nativeList) => nativeList.AsReadOnlySpan(); + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeList left, NativeList right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeList left, NativeList right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Array); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() => MemoryMarshal.CreateSpan(ref *_handle->Array, _handle->Length); + + /// + /// As span + /// + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int length) => MemoryMarshal.CreateSpan(ref *_handle->Array, length); + + /// + /// As span + /// + /// Start + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int start, int length) => MemoryMarshal.CreateSpan(ref *(_handle->Array + start), length); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan() => MemoryMarshal.CreateReadOnlySpan(ref *_handle->Array, _handle->Length); + + /// + /// As readOnly span + /// + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int length) => MemoryMarshal.CreateReadOnlySpan(ref *_handle->Array, length); + + /// + /// As readOnly span + /// + /// Start + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int start, int length) => MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + start), length); + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _handle->Version++; + _handle->Size = 0; + } + + /// + /// Add + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(in T item) + { + _handle->Version++; + var size = _handle->Size; + if ((uint)size < (uint)_handle->Length) + { + _handle->Size = size + 1; + _handle->Array[size] = item; + } + else + { + Grow(size + 1); + _handle->Size = size + 1; + _handle->Array[size] = item; + } + } + + /// + /// Add range + /// + /// Collection + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(in NativeList collection) + { + var count = collection._handle->Size; + if (count > 0) + { + if (_handle->Length - _handle->Size < count) + Grow(checked(_handle->Size + count)); + Unsafe.CopyBlockUnaligned(_handle->Array + _handle->Size, collection._handle->Array, (uint)(collection._handle->Size * sizeof(T))); + _handle->Size += count; + _handle->Version++; + } + } + + /// + /// Insert + /// + /// Index + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Insert(int index, in T item) + { + if ((uint)index > (uint)_handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "ListInsert"); + if (_handle->Size == _handle->Length) + Grow(_handle->Size + 1); + if (index < _handle->Size) + Unsafe.CopyBlockUnaligned(_handle->Array + (index + 1), _handle->Array + index, (uint)((_handle->Size - index) * sizeof(T))); + _handle->Array[index] = item; + _handle->Size++; + _handle->Version++; + } + + /// + /// Insert + /// + /// Index + /// Collection + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, in NativeList collection) + { + if ((uint)index > (uint)_handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLessOrEqual"); + var count = collection._handle->Size; + if (count > 0) + { + if (_handle->Length - _handle->Size < count) + Grow(checked(_handle->Size + count)); + if (index < _handle->Size) + Unsafe.CopyBlockUnaligned(_handle->Array + index + count, _handle->Array + index, (uint)((_handle->Size - index) * sizeof(T))); + if (this == collection) + { + Unsafe.CopyBlockUnaligned(_handle->Array + index, _handle->Array, (uint)(index * sizeof(T))); + Unsafe.CopyBlockUnaligned(_handle->Array + index * 2, _handle->Array + index + count, (uint)((_handle->Size - index) * sizeof(T))); + } + else + { + Unsafe.CopyBlockUnaligned(_handle->Array + index, collection._handle->Array, (uint)(collection._handle->Size * sizeof(T))); + } + + _handle->Size += count; + _handle->Version++; + } + } + + /// + /// Remove + /// + /// Item + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in T item) + { + var index = IndexOf(item); + if (index >= 0) + { + RemoveAt(index); + return true; + } + + return false; + } + + /// + /// Remove at + /// + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) + { + if ((uint)index >= (uint)_handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLess"); + _handle->Size--; + if (index < _handle->Size) + Unsafe.CopyBlockUnaligned(_handle->Array + index, _handle->Array + (index + 1), (uint)((_handle->Size - index) * sizeof(T))); + _handle->Version++; + } + + /// + /// Remove range + /// + /// Index + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, "NeedNonNegNum"); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "NeedNonNegNum"); + var offset = _handle->Size - index; + if (offset < count) + throw new ArgumentOutOfRangeException(offset.ToString(), "InvalidOffLen"); + if (count > 0) + { + _handle->Size -= count; + if (index < _handle->Size) + Unsafe.CopyBlockUnaligned(_handle->Array + index, _handle->Array + (index + count), (uint)((_handle->Size - index) * sizeof(T))); + _handle->Version++; + } + } + + /// + /// Reverse + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reverse() + { + if (_handle->Size > 1) + MemoryMarshal.CreateSpan(ref *_handle->Array, _handle->Size).Reverse(); + _handle->Version++; + } + + /// + /// Reverse + /// + /// Index + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reverse(int index, int count) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, "NeedNonNegNum"); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "NeedNonNegNum"); + var offset = _handle->Size - index; + if (offset < count) + throw new ArgumentOutOfRangeException(offset.ToString(), "InvalidOffLen"); + if (count > 1) + MemoryMarshal.CreateSpan(ref *(_handle->Array + index), count).Reverse(); + _handle->Version++; + } + + /// + /// Contains + /// + /// Item + /// Contains + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(in T item) => _handle->Size != 0 && IndexOf(item) >= 0; + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (_handle->Length < capacity) + Grow(capacity); + return _handle->Length; + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess() + { + var threshold = (int)(_handle->Length * 0.9); + if (_handle->Size < threshold) + Capacity = _handle->Size; + return _handle->Length; + } + + /// + /// Grow + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Grow(int capacity) + { + var newCapacity = 2 * _handle->Length; + if ((uint)newCapacity > 2147483591) + newCapacity = 2147483591; + var expected = _handle->Length + 4; + newCapacity = newCapacity > expected ? newCapacity : expected; + if (newCapacity < capacity) + newCapacity = capacity; + Capacity = newCapacity; + } + + /// + /// Index of + /// + /// Item + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(in T item) => _handle->Size == 0 ? -1 : MemoryMarshal.CreateReadOnlySpan(ref *_handle->Array, _handle->Size).IndexOf(item); + + /// + /// Index of + /// + /// Item + /// Index + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(in T item, int index) + { + if (_handle->Size == 0) + return -1; + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, "NeedNonNegNum"); + if (index > _handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLessOrEqual"); + return MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + index), _handle->Size - index).IndexOf(item); + } + + /// + /// Index of + /// + /// Item + /// Index + /// Count + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(in T item, int index, int count) + { + if (_handle->Size == 0) + return -1; + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, "NeedNonNegNum"); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "NeedNonNegNum"); + if (index > _handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLessOrEqual"); + if (index > _handle->Size - count) + throw new ArgumentOutOfRangeException(nameof(count), count, "BiggerThanCollection"); + return MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + index), count).IndexOf(item); + } + + /// + /// Last index of + /// + /// Item + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int LastIndexOf(in T item) => _handle->Size == 0 ? -1 : MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + (_handle->Size - 1)), _handle->Size).LastIndexOf(item); + + /// + /// Last index of + /// + /// Item + /// Index + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int LastIndexOf(in T item, int index) + { + if (_handle->Size == 0) + return -1; + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, "NeedNonNegNum"); + if (index >= _handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "IndexMustBeLess"); + return MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + index), index + 1).LastIndexOf(item); + } + + /// + /// Last index of + /// + /// Item + /// Index + /// Count + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int LastIndexOf(in T item, int index, int count) + { + if (_handle->Size == 0) + return -1; + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, "NeedNonNegNum"); + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), count, "NeedNonNegNum"); + if (index >= _handle->Size) + throw new ArgumentOutOfRangeException(nameof(index), index, "BiggerThanCollection"); + if (count > index + 1) + throw new ArgumentOutOfRangeException(nameof(count), count, "BiggerThanCollection"); + return MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + index), count).LastIndexOf(item); + } + + /// + /// Empty + /// + public static NativeList Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeList + /// + private readonly NativeList _nativeList; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Index + /// + private int _index; + + /// + /// Current + /// + private T _current; + + /// + /// Structure + /// + /// NativeList + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeList nativeList) + { + _nativeList = nativeList; + _index = 0; + _version = nativeList._handle->Version; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + var localList = _nativeList; + if (_version == localList._handle->Version && (uint)_index < (uint)localList._handle->Size) + { + _current = localList._handle->Array[_index]; + _index++; + return true; + } + + if (_version != _nativeList._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + _index = _nativeList._handle->Size + 1; + _current = default; + return false; + } + + /// + /// Current + /// + public T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeList.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeList.cs.meta new file mode 100644 index 00000000..a32b82dc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1712d881a1474a22b9d27d2835a98c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryAllocator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryAllocator.cs new file mode 100644 index 00000000..10986fb3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryAllocator.cs @@ -0,0 +1,233 @@ +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET7_0_OR_GREATER +using System.Runtime.Intrinsics; +#endif + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory allocator + /// + public static unsafe class NativeMemoryAllocator + { + /// + /// Alloc + /// + /// Byte count + /// Memory + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* Alloc(uint byteCount) + { +#if NET6_0_OR_GREATER + return NativeMemory.Alloc(byteCount); +#else + return (void*)Marshal.AllocHGlobal((nint)byteCount); +#endif + } + + /// + /// Alloc zeroed + /// + /// Byte count + /// Memory + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void* AllocZeroed(uint byteCount) + { +#if NET6_0_OR_GREATER + return NativeMemory.AllocZeroed(byteCount, 1); +#else + var ptr = (void*)Marshal.AllocHGlobal((nint)byteCount); + Unsafe.InitBlockUnaligned(ptr, 0, byteCount); + return ptr; +#endif + } + + /// + /// Free + /// + /// Pointer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Free(void* ptr) + { +#if NET6_0_OR_GREATER + NativeMemory.Free(ptr); +#else + Marshal.FreeHGlobal((nint)ptr); +#endif + } + + /// + /// Copy + /// + /// Destination + /// Source + /// Byte count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Copy(void* destination, void* source, uint byteCount) => Unsafe.CopyBlockUnaligned(destination, source, byteCount); + + /// + /// Move + /// + /// Destination + /// Source + /// Byte count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Move(void* destination, void* source, uint byteCount) => Buffer.MemoryCopy(source, destination, byteCount, byteCount); + + /// + /// Set + /// + /// Start address + /// Value + /// Byte count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Set(void* startAddress, byte value, uint byteCount) => Unsafe.InitBlockUnaligned(startAddress, value, byteCount); + + /// + /// Compare + /// + /// Left + /// Right + /// Byte count + /// Sequences equal + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Compare(void* left, void* right, uint byteCount) + { + ref var first = ref *(byte*)left; + ref var second = ref *(byte*)right; + nuint length = byteCount; + if (length >= (nuint)sizeof(nuint)) + { + if (!Unsafe.AreSame(ref first, ref second)) + { +#if NET7_0_OR_GREATER + if (Vector128.IsHardwareAccelerated) + { +#if NET8_0_OR_GREATER + if (Vector512.IsHardwareAccelerated && length >= (nuint)Vector512.Count) + { + nuint offset = 0; + var lengthToExamine = length - (nuint)Vector512.Count; + if (lengthToExamine != 0) + { + do + { + if (Vector512.LoadUnsafe(ref first, offset) != Vector512.LoadUnsafe(ref second, offset)) + return false; + offset += (nuint)Vector512.Count; + } while (lengthToExamine > offset); + } + + return Vector512.LoadUnsafe(ref first, lengthToExamine) == Vector512.LoadUnsafe(ref second, lengthToExamine); + } +#endif + if (Vector256.IsHardwareAccelerated && length >= (nuint)Vector256.Count) + { + nuint offset = 0; + var lengthToExamine = length - (nuint)Vector256.Count; + if (lengthToExamine != 0) + { + do + { + if (Vector256.LoadUnsafe(ref first, offset) != Vector256.LoadUnsafe(ref second, offset)) + return false; + offset += (nuint)Vector256.Count; + } while (lengthToExamine > offset); + } + + return Vector256.LoadUnsafe(ref first, lengthToExamine) == Vector256.LoadUnsafe(ref second, lengthToExamine); + } + + if (length >= (nuint)Vector128.Count) + { + nuint offset = 0; + var lengthToExamine = length - (nuint)Vector128.Count; + if (lengthToExamine != 0) + { + do + { + if (Vector128.LoadUnsafe(ref first, offset) != Vector128.LoadUnsafe(ref second, offset)) + return false; + offset += (nuint)Vector128.Count; + } while (lengthToExamine > offset); + } + + return Vector128.LoadUnsafe(ref first, lengthToExamine) == Vector128.LoadUnsafe(ref second, lengthToExamine); + } + } + + if (IntPtr.Size == 8 && Vector128.IsHardwareAccelerated) + { + var offset = length - (nuint)sizeof(nuint); + var differentBits = Unsafe.ReadUnaligned(ref first) - Unsafe.ReadUnaligned(ref second); + differentBits |= Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, offset)) - Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, offset)); + return differentBits == 0; + } + else +#endif + { + nuint offset = 0; + var lengthToExamine = length - (nuint)sizeof(nuint); + if (lengthToExamine > 0) + { + do + { +#if NET7_0_OR_GREATER + if (Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, offset)) != Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, offset))) +#else + if (Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, (nint)offset)) != Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, (nint)offset))) +#endif + return false; + offset += (nuint)sizeof(nuint); + } while (lengthToExamine > offset); + } +#if NET7_0_OR_GREATER + return Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, lengthToExamine)) == Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, lengthToExamine)); +#else + return Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, (nint)lengthToExamine)) == Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, (nint)lengthToExamine)); +#endif + } + } + + return true; + } + + if (length < sizeof(uint) || IntPtr.Size != 8) + { + uint differentBits = 0; + var offset = length & 2; + if (offset != 0) + { + differentBits = Unsafe.ReadUnaligned(ref first); + differentBits -= Unsafe.ReadUnaligned(ref second); + } + + if ((length & 1) != 0) +#if NET7_0_OR_GREATER + differentBits |= Unsafe.AddByteOffset(ref first, offset) - (uint)Unsafe.AddByteOffset(ref second, offset); +#else + differentBits |= Unsafe.AddByteOffset(ref first, (nint)offset) - (uint)Unsafe.AddByteOffset(ref second, (nint)offset); +#endif + return differentBits == 0; + } + else + { + var offset = length - sizeof(uint); + var differentBits = Unsafe.ReadUnaligned(ref first) - Unsafe.ReadUnaligned(ref second); +#if NET7_0_OR_GREATER + differentBits |= Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, offset)) - Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, offset)); +#else + differentBits |= Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref first, (nint)offset)) - Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref second, (nint)offset)); +#endif + return differentBits == 0; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryAllocator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryAllocator.cs.meta new file mode 100644 index 00000000..b33dc5ed --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryAllocator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 13341ceb5e7764b089271e473be432e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryArray.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryArray.cs new file mode 100644 index 00000000..7b1e4dc4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryArray.cs @@ -0,0 +1,329 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory array + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeMemoryArray : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Array + /// + private readonly T* _array; + + /// + /// Length + /// + private readonly int _length; + + /// + /// Structure + /// + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryArray(int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _array = (T*)NativeMemoryAllocator.Alloc((uint)(length * sizeof(T))); + _length = length; + } + + /// + /// Structure + /// + /// Length + /// Zeroed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryArray(int length, bool zeroed) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _array = zeroed ? (T*)NativeMemoryAllocator.AllocZeroed((uint)(length * sizeof(T))) : (T*)NativeMemoryAllocator.Alloc((uint)(length * sizeof(T))); + _length = length; + } + + /// + /// Structure + /// + /// Array + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryArray(T* array, int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _array = array; + _length = length; + } + + /// + /// Is created + /// + public bool IsCreated => _array != null; + + /// + /// Is empty + /// + public bool IsEmpty => _length == 0; + + /// + /// Get reference + /// + /// Index + public T* this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _array + index; + } + + /// + /// Get reference + /// + /// Index + public T* this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _array + index; + } + + /// + /// Array + /// + public T* Array => _array; + + /// + /// Length + /// + public int Length => _length; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMemoryArray other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeMemoryArray nativeMemoryArray && nativeMemoryArray == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_array; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeMemoryArray<{typeof(T).Name}>[{_length}]"; + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Span(NativeMemoryArray nativeMemoryArray) => nativeMemoryArray.AsSpan(); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(NativeMemoryArray nativeMemoryArray) => nativeMemoryArray.AsReadOnlySpan(); + + /// + /// As native array + /// + /// Native memory array + /// NativeArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeArray(NativeMemoryArray nativeMemoryArray) => new(nativeMemoryArray._array, nativeMemoryArray._length); + + /// + /// As native memory array + /// + /// Native array + /// NativeMemoryArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeMemoryArray(NativeArray nativeArray) => new(nativeArray.Array, nativeArray.Length); + + /// + /// As native array segment + /// + /// Native memory array + /// NativeArraySegment + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeArraySegment(NativeMemoryArray nativeMemoryArray) => new(nativeMemoryArray._array, nativeMemoryArray._length); + + /// + /// As native memory array + /// + /// Native array segment + /// NativeMemoryArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeMemoryArray(NativeArraySegment nativeArraySegment) => new(nativeArraySegment.Array, nativeArraySegment.Offset + nativeArraySegment.Count); + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMemoryArray left, NativeMemoryArray right) => left._length == right._length && left._array == right._array; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMemoryArray left, NativeMemoryArray right) => left._length != right._length || left._array != right._array; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_array == null) + return; + NativeMemoryAllocator.Free(_array); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => Unsafe.InitBlockUnaligned(_array, 0, (uint)(_length * sizeof(T))); + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() => MemoryMarshal.CreateSpan(ref *_array, _length); + + /// + /// As span + /// + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int length) => MemoryMarshal.CreateSpan(ref *_array, length); + + /// + /// As span + /// + /// Start + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int start, int length) => MemoryMarshal.CreateSpan(ref *(_array + start), length); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan() => MemoryMarshal.CreateReadOnlySpan(ref *_array, _length); + + /// + /// As readOnly span + /// + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int length) => MemoryMarshal.CreateReadOnlySpan(ref *_array, length); + + /// + /// As readOnly span + /// + /// Start + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int start, int length) => MemoryMarshal.CreateReadOnlySpan(ref *(_array + start), length); + + /// + /// Empty + /// + public static NativeMemoryArray Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public ref struct Enumerator + { + /// + /// NativeMemoryArray + /// + private readonly NativeMemoryArray _nativeMemoryArray; + + /// + /// Index + /// + private int _index; + + /// + /// Structure + /// + /// NativeMemoryArray + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeMemoryArray nativeMemoryArray) + { + _nativeMemoryArray = nativeMemoryArray; + _index = -1; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + var index = _index + 1; + if (index < _nativeMemoryArray._length) + { + _index = index; + return true; + } + + return false; + } + + /// + /// Current + /// + public T* Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _nativeMemoryArray[_index]; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryArray.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryArray.cs.meta new file mode 100644 index 00000000..0b108620 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryArray.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d91ae680ac25348b7baebf74f9f91122 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryBucket.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryBucket.cs new file mode 100644 index 00000000..01b8d603 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryBucket.cs @@ -0,0 +1,199 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory bucket + /// + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeMemoryBucket : IDisposable, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeMemoryBucketHandle + { + /// + /// Size + /// + public int Size; + + /// + /// Length + /// + public int Length; + + /// + /// Array + /// + public void** Array; + + /// + /// Index + /// + public int Index; + + /// + /// Memory pool + /// + public NativeMemoryPool MemoryPool; + } + + /// + /// Handle + /// + private readonly NativeMemoryBucketHandle* _handle; + + /// + /// Structure + /// + /// Size + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryBucket(int size, int length) + { + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size), size, "MustBePositive"); + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + _handle = (NativeMemoryBucketHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeMemoryBucketHandle)); + _handle->Size = size; + _handle->Length = length; + _handle->Array = (void**)NativeMemoryAllocator.AllocZeroed((uint)(size * sizeof(void*))); + _handle->Index = 0; + _handle->MemoryPool = new NativeMemoryPool(size, length, 0); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Index == 0; + + /// + /// Is full + /// + public bool IsFull => _handle->Index == _handle->Size; + + /// + /// Size + /// + public int Size => _handle->Size; + + /// + /// Length + /// + public int Length => _handle->Length; + + /// + /// Count + /// + public int Count => _handle->Index; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMemoryBucket other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeMemoryBucket nativeMemoryBucket && nativeMemoryBucket == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => "NativeMemoryBucket"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMemoryBucket left, NativeMemoryBucket right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMemoryBucket left, NativeMemoryBucket right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Array); + _handle->MemoryPool.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Rent buffer + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void* Rent() + { + void* buffer = null; + if (_handle->Index < _handle->Size) + { + buffer = _handle->Array[_handle->Index]; + _handle->Array[_handle->Index++] = null; + } + + if (buffer == null) + buffer = _handle->MemoryPool.Rent(); + return buffer; + } + + /// + /// Return buffer + /// + /// Pointer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(void* ptr) + { + if (_handle->Index != 0) + _handle->Array[--_handle->Index] = ptr; + else + _handle->MemoryPool.Return(ptr); + } + + /// + /// Empty + /// + public static NativeMemoryBucket Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryBucket.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryBucket.cs.meta new file mode 100644 index 00000000..40665618 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryBucket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3fda080db31784f1d9266b8edc496b07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryPool.cs new file mode 100644 index 00000000..2c009cfe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryPool.cs @@ -0,0 +1,388 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory pool + /// + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeMemoryPool : IDisposable, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeMemoryPoolHandle + { + /// + /// Slab + /// + public NativeMemorySlab* Slab; + + /// + /// Free slab + /// + public NativeMemorySlab* FreeSlab; + + /// + /// Slabs + /// + public int Slabs; + + /// + /// Free slabs + /// + public int FreeSlabs; + + /// + /// Max free slabs + /// + public int MaxFreeSlabs; + + /// + /// Size + /// + public int Size; + + /// + /// Length + /// + public int Length; + } + + /// + /// Slab + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeMemorySlab + { + /// + /// Next + /// + public NativeMemorySlab* Next; + + /// + /// Previous + /// + public NativeMemorySlab* Previous; + + /// + /// Node + /// + public NativeMemoryNode* Node; + + /// + /// Count + /// + public int Count; + } + + /// + /// Node + /// + [StructLayout(LayoutKind.Explicit)] + private struct NativeMemoryNode + { + /// + /// Slab + /// + [FieldOffset(0)] public NativeMemorySlab* Slab; + + /// + /// Next + /// + [FieldOffset(0)] public NativeMemoryNode* Next; + } + + /// + /// Handle + /// + private readonly NativeMemoryPoolHandle* _handle; + + /// + /// Structure + /// + /// Size + /// Length + /// Max free slabs + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryPool(int size, int length, int maxFreeSlabs) + { + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size), size, "MustBePositive"); + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + if (maxFreeSlabs < 0) + throw new ArgumentOutOfRangeException(nameof(maxFreeSlabs), maxFreeSlabs, "MustBeNonNegative"); + var nodeSize = sizeof(NativeMemoryNode) + length; + var array = (byte*)NativeMemoryAllocator.Alloc((uint)(sizeof(NativeMemorySlab) + size * nodeSize)); + var slab = (NativeMemorySlab*)array; + slab->Next = slab; + slab->Previous = slab; + array += sizeof(NativeMemorySlab); + NativeMemoryNode* next = null; + for (var i = size - 1; i >= 0; --i) + { + var node = (NativeMemoryNode*)(array + i * nodeSize); + node->Next = next; + next = node; + } + + slab->Node = next; + slab->Count = size; + _handle = (NativeMemoryPoolHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeMemoryPoolHandle)); + _handle->Slab = slab; + _handle->FreeSlab = null; + _handle->Slabs = 1; + _handle->FreeSlabs = 0; + _handle->MaxFreeSlabs = maxFreeSlabs; + _handle->Size = size; + _handle->Length = length; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Slabs + /// + public int Slabs => _handle->Slabs; + + /// + /// Free slabs + /// + public int FreeSlabs => _handle->FreeSlabs; + + /// + /// Max free slabs + /// + public int MaxFreeSlabs => _handle->MaxFreeSlabs; + + /// + /// Size + /// + public int Size => _handle->Size; + + /// + /// Length + /// + public int Length => _handle->Length; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMemoryPool other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeMemoryPool nativeMemoryPool && nativeMemoryPool == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => "NativeMemoryPool"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMemoryPool left, NativeMemoryPool right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMemoryPool left, NativeMemoryPool right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + var node = _handle->Slab; + while (_handle->Slabs > 0) + { + _handle->Slabs--; + var temp = node; + node = node->Next; + NativeMemoryAllocator.Free(temp); + } + + node = _handle->FreeSlab; + while (_handle->FreeSlabs > 0) + { + _handle->FreeSlabs--; + var temp = node; + node = node->Next; + NativeMemoryAllocator.Free(temp); + } + + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Rent buffer + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void* Rent() + { + NativeMemoryNode* node; + var slab = _handle->Slab; + if (slab->Count == 0) + { + _handle->Slab = slab->Next; + slab = _handle->Slab; + if (slab->Count == 0) + { + var size = _handle->Size; + if (_handle->FreeSlabs == 0) + { + var nodeSize = sizeof(NativeMemoryNode) + _handle->Length; + var array = (byte*)NativeMemoryAllocator.Alloc((uint)(sizeof(NativeMemorySlab) + size * nodeSize)); + slab = (NativeMemorySlab*)array; + array += sizeof(NativeMemorySlab); + NativeMemoryNode* next = null; + for (var i = size - 1; i >= 0; --i) + { + node = (NativeMemoryNode*)(array + i * nodeSize); + node->Next = next; + next = node; + } + + slab->Node = next; + } + else + { + slab = _handle->FreeSlab; + _handle->FreeSlab = slab->Next; + _handle->FreeSlabs--; + } + + slab->Next = _handle->Slab; + slab->Previous = _handle->Slab->Previous; + slab->Count = size; + _handle->Slab->Previous->Next = slab; + _handle->Slab->Previous = slab; + _handle->Slab = slab; + _handle->Slabs++; + } + } + + node = slab->Node; + slab->Node = node->Next; + node->Slab = slab; + slab->Count--; + return (byte*)node + sizeof(NativeMemoryNode); + } + + /// + /// Return buffer + /// + /// Pointer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(void* ptr) + { + var node = (NativeMemoryNode*)((byte*)ptr - sizeof(NativeMemoryNode)); + var slab = node->Slab; + slab->Count++; + if (slab->Count == _handle->Size && slab != _handle->Slab) + { + slab->Previous->Next = slab->Next; + slab->Next->Previous = slab->Previous; + if (_handle->FreeSlabs == _handle->MaxFreeSlabs) + { + NativeMemoryAllocator.Free(slab); + } + else + { + node->Next = slab->Node; + slab->Node = node; + slab->Next = _handle->FreeSlab; + _handle->FreeSlab = slab; + _handle->FreeSlabs++; + } + + _handle->Slabs--; + return; + } + + node->Next = slab->Node; + slab->Node = node; + } + + /// + /// Trim excess + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void TrimExcess() + { + var node = _handle->FreeSlab; + while (_handle->FreeSlabs > 0) + { + _handle->FreeSlabs--; + var temp = node; + node = node->Next; + NativeMemoryAllocator.Free(temp); + } + + _handle->FreeSlab = node; + } + + /// + /// Trim excess + /// + /// Remaining free slabs + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void TrimExcess(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + var node = _handle->FreeSlab; + while (_handle->FreeSlabs > capacity) + { + _handle->FreeSlabs--; + var temp = node; + node = node->Next; + NativeMemoryAllocator.Free(temp); + } + + _handle->FreeSlab = node; + } + + /// + /// Empty + /// + public static NativeMemoryPool Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryPool.cs.meta new file mode 100644 index 00000000..a606ec90 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 837e2433d114643ffb141887b424283e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReader.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReader.cs new file mode 100644 index 00000000..3ca294ae --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReader.cs @@ -0,0 +1,274 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory reader + /// + [StructLayout(LayoutKind.Sequential)] + public unsafe ref struct NativeMemoryReader + { + /// + /// Array + /// + public readonly byte* Array; + + /// + /// Length + /// + public readonly int Length; + + /// + /// Position + /// + public int Position; + + /// + /// Structure + /// + /// Array + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryReader(byte* array, int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + Array = array; + Length = length; + Position = 0; + } + + /// + /// Remaining + /// + public int Remaining => Length - Position; + + /// + /// Get reference + /// + /// Index + public byte* this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Array + index; + } + + /// + /// Get reference + /// + /// Index + public byte* this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Array + index; + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMemoryReader other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => throw new NotSupportedException("Cannot call Equals on NativeMemoryReader"); + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => HashCode.Combine((int)(nint)Array, Length, Position); + + /// + /// To string + /// + /// String + public override string ToString() => "NativeMemoryReader"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMemoryReader left, NativeMemoryReader right) => left.Array == right.Array && left.Length == right.Length && left.Position == right.Position; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMemoryReader left, NativeMemoryReader right) => left.Array != right.Array || left.Length != right.Length || left.Position != right.Position; + + /// + /// Advance + /// + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Advance(int count) + { + var newPosition = Position + count; + if (newPosition < 0 || newPosition > Length) + throw new ArgumentOutOfRangeException(nameof(count), "Cannot advance past the end of the buffer."); + Position = newPosition; + } + + /// + /// Try advance + /// + /// Count + /// Advanced + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryAdvance(int count) + { + var newPosition = Position + count; + if (newPosition < 0 || newPosition > Length) + return false; + Position = newPosition; + return true; + } + + /// + /// Read + /// + /// object + /// Type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Read(T* obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {sizeof(T)}, but buffer length is {Remaining}."); + Unsafe.CopyBlockUnaligned(obj, Array + Position, (uint)sizeof(T)); + Position += sizeof(T); + } + + /// + /// Try read + /// + /// object + /// Type + /// Read + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryRead(T* obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + return false; + Unsafe.CopyBlockUnaligned(obj, Array + Position, (uint)sizeof(T)); + Position += sizeof(T); + return true; + } + + /// + /// Read + /// + /// object + /// Count + /// Type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Read(T* obj, int count) where T : unmanaged + { + count *= sizeof(T); + if (Position + count > Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {count}, but buffer length is {Remaining}."); + Unsafe.CopyBlockUnaligned(obj, Array + Position, (uint)count); + Position += count; + } + + /// + /// Try read + /// + /// object + /// Count + /// Type + /// Read + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryRead(T* obj, int count) where T : unmanaged + { + count *= sizeof(T); + if (Position + count > Length) + return false; + Unsafe.CopyBlockUnaligned(obj, Array + Position, (uint)count); + Position += count; + return true; + } + + /// + /// Read + /// + /// object + /// Type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Read(ref T obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {sizeof(T)}, but buffer length is {Remaining}."); + obj = Unsafe.ReadUnaligned(Array + Position); + Position += sizeof(T); + } + + /// + /// Try read + /// + /// object + /// Type + /// Read + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryRead(ref T obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + return false; + obj = Unsafe.ReadUnaligned(Array + Position); + Position += sizeof(T); + return true; + } + + /// + /// Read bytes + /// + /// Buffer + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ReadBytes(byte* buffer, int length) + { + if (Position + length > Length) + throw new ArgumentOutOfRangeException(nameof(length), $"Requires size is {length}, but buffer length is {Remaining}."); + Unsafe.CopyBlockUnaligned(buffer, Array + Position, (uint)length); + Position += length; + } + + /// + /// Try read bytes + /// + /// Buffer + /// Length + /// Read + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryReadBytes(byte* buffer, int length) + { + if (Position + length > Length) + return false; + Unsafe.CopyBlockUnaligned(buffer, Array + Position, (uint)length); + Position += length; + return true; + } + + /// + /// Empty + /// + public static NativeMemoryReader Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReader.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReader.cs.meta new file mode 100644 index 00000000..ba11c80c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c2689961a97f4777976aa6ac8bf9071 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReaderExtensions.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReaderExtensions.cs new file mode 100644 index 00000000..c38538ef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReaderExtensions.cs @@ -0,0 +1,55 @@ +using System.Runtime.CompilerServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory reader extensions + /// + public static unsafe class NativeMemoryReaderExtensions + { + /// + /// Read + /// + /// Reader + /// Type + /// object + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Read(this ref NativeMemoryReader reader) where T : unmanaged + { + if (reader.Position + sizeof(T) > reader.Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {sizeof(T)}, but buffer length is {reader.Remaining}."); + var obj = Unsafe.ReadUnaligned(reader.Array + reader.Position); + reader.Position += sizeof(T); + return obj; + } + + /// + /// Try read + /// + /// Reader + /// object + /// Type + /// Read + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryRead(this ref NativeMemoryReader reader, out T obj) where T : unmanaged + { + if (reader.Position + sizeof(T) > reader.Length) + { + obj = default; + return false; + } + + obj = Unsafe.ReadUnaligned(reader.Array + reader.Position); + reader.Position += sizeof(T); + return true; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReaderExtensions.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReaderExtensions.cs.meta new file mode 100644 index 00000000..e4c7dd7f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryReaderExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2fdfdaa2ada744fb89338cd5acdfbf32 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryStream.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryStream.cs new file mode 100644 index 00000000..81c3ef1d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryStream.cs @@ -0,0 +1,571 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.IO; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory stream + /// + [StructLayout(LayoutKind.Sequential)] + public unsafe struct NativeMemoryStream : IDisposable, IEquatable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeMemoryStreamHandle + { + /// + /// Array + /// + public byte* Array; + + /// + /// Position + /// + public int Position; + + /// + /// Length + /// + public int Length; + + /// + /// Capacity + /// + public int Capacity; + } + + /// + /// Handle + /// + private readonly NativeMemoryStreamHandle* _handle; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryStream(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeMemoryStreamHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeMemoryStreamHandle)); + _handle->Array = (byte*)NativeMemoryAllocator.Alloc((uint)capacity); + _handle->Position = 0; + _handle->Length = 0; + _handle->Capacity = capacity; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Length == 0; + + /// + /// Get reference + /// + /// Index + public ref byte this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Get reference + /// + /// Index + public ref byte this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Can read + /// + public bool CanRead => IsCreated; + + /// + /// Can seek + /// + public bool CanSeek => IsCreated; + + /// + /// Can write + /// + public bool CanWrite => IsCreated; + + /// + /// Length + /// + public int Length + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + EnsureNotClosed(); + return _handle->Length; + } + } + + /// + /// Position + /// + public int Position + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + EnsureNotClosed(); + return _handle->Position; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + if (value < 0) + throw new ArgumentOutOfRangeException(nameof(Position), value, "MustBeNonNegative"); + EnsureNotClosed(); + _handle->Position = value; + } + } + + /// + /// Capacity + /// + public int Capacity + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + EnsureNotClosed(); + return _handle->Capacity; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + EnsureNotClosed(); + if (value < _handle->Length) + throw new ArgumentOutOfRangeException(nameof(Capacity), value, "SmallCapacity"); + if (value != _handle->Capacity) + { + if (value > 0) + { + var newBuffer = (byte*)NativeMemoryAllocator.Alloc((uint)value); + if (_handle->Length > 0) + Unsafe.CopyBlockUnaligned(newBuffer, _handle->Array, (uint)_handle->Length); + NativeMemoryAllocator.Free(_handle->Array); + _handle->Array = newBuffer; + } + else + { + NativeMemoryAllocator.Free(_handle->Array); + _handle->Array = (byte*)NativeMemoryAllocator.Alloc(0); + } + + _handle->Capacity = value; + } + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMemoryStream other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeMemoryStream nativeMemoryStream && nativeMemoryStream == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeMemoryStream<{_handle->Length}>"; + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Span(NativeMemoryStream nativeList) => nativeList.AsSpan(); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(NativeMemoryStream nativeList) => nativeList.AsReadOnlySpan(); + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMemoryStream left, NativeMemoryStream right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMemoryStream left, NativeMemoryStream right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Array); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() => MemoryMarshal.CreateSpan(ref *_handle->Array, _handle->Length); + + /// + /// As span + /// + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int length) => MemoryMarshal.CreateSpan(ref *_handle->Array, length); + + /// + /// As span + /// + /// Start + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int start, int length) => MemoryMarshal.CreateSpan(ref *(_handle->Array + start), length); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan() => MemoryMarshal.CreateReadOnlySpan(ref *_handle->Array, _handle->Length); + + /// + /// As readOnly span + /// + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int length) => MemoryMarshal.CreateReadOnlySpan(ref *_handle->Array, length); + + /// + /// As readOnly span + /// + /// Start + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int start, int length) => MemoryMarshal.CreateReadOnlySpan(ref *(_handle->Array + start), length); + + /// + /// Get buffer + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public byte* GetBuffer() => _handle->Array; + + /// + /// Seek + /// + /// Offset + /// Seek origin + /// Position + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Seek(int offset, SeekOrigin loc) + { + if (offset > 2147483647) + throw new ArgumentOutOfRangeException(nameof(offset), offset, "StreamLength"); + EnsureNotClosed(); + switch (loc) + { + case SeekOrigin.Begin: + { + if (offset < 0) + throw new IOException("IO_SeekBeforeBegin"); + _handle->Position = offset; + break; + } + case SeekOrigin.Current: + { + var tempPosition = unchecked(_handle->Position + offset); + if (tempPosition < 0) + throw new IOException("IO_SeekBeforeBegin"); + _handle->Position = tempPosition; + break; + } + case SeekOrigin.End: + { + var tempPosition = unchecked(_handle->Length + offset); + if (tempPosition < 0) + throw new IOException("IO_SeekBeforeBegin"); + _handle->Position = tempPosition; + break; + } + default: + throw new ArgumentException("InvalidSeekOrigin"); + } + + return _handle->Position; + } + + /// + /// Set length + /// + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetLength(int length) + { + if (length < 0 || length > 2147483647) + throw new ArgumentOutOfRangeException(nameof(length), length, "StreamLength"); + EnsureNotClosed(); + var allocatedNewArray = EnsureCapacity(length); + if (!allocatedNewArray && length > _handle->Length) + Unsafe.InitBlock(_handle->Array + _handle->Length, 0, (uint)(length - _handle->Length)); + _handle->Length = length; + if (_handle->Position > length) + _handle->Position = length; + } + + /// + /// Read + /// + /// Buffer + /// Offset + /// Count + /// Bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Read(byte* buffer, int offset, int count) + { + EnsureNotClosed(); + var n = _handle->Length - _handle->Position; + if (n > count) + n = count; + if (n <= 0) + return 0; + if (n <= 8) + { + var byteCount = n; + while (--byteCount >= 0) + buffer[offset + byteCount] = _handle->Array[_handle->Position + byteCount]; + } + else + { + Unsafe.CopyBlockUnaligned(buffer + offset, _handle->Array + _handle->Position, (uint)n); + } + + _handle->Position += n; + return n; + } + + /// + /// Read + /// + /// Buffer + /// Bytes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Read(Span buffer) + { + EnsureNotClosed(); + var size = _handle->Length - _handle->Position; + var n = size < buffer.Length ? size : buffer.Length; + if (n <= 0) + return 0; + Unsafe.CopyBlockUnaligned(ref buffer[0], ref *(_handle->Array + _handle->Position), (uint)n); + _handle->Position += n; + return n; + } + + /// + /// Read + /// + /// Byte + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ReadByte() + { + EnsureNotClosed(); + return _handle->Position >= _handle->Length ? -1 : _handle->Array[_handle->Position++]; + } + + /// + /// Write + /// + /// Buffer + /// Offset + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Write(byte* buffer, int offset, int count) + { + EnsureNotClosed(); + var i = _handle->Position + count; + if (i < 0) + throw new IOException("IO_StreamTooLong"); + if (i > _handle->Length) + { + var mustZero = _handle->Position > _handle->Length; + if (i > _handle->Capacity) + { + var allocatedNewArray = EnsureCapacity(i); + if (allocatedNewArray) + mustZero = false; + } + + if (mustZero) + Unsafe.InitBlock(_handle->Array + _handle->Length, 0, (uint)(i - _handle->Length)); + _handle->Length = i; + } + + if (count <= 8 && buffer != _handle->Array) + { + var byteCount = count; + while (--byteCount >= 0) + _handle->Array[_handle->Position + byteCount] = buffer[offset + byteCount]; + } + else + { + Unsafe.CopyBlockUnaligned(_handle->Array + _handle->Position, buffer + offset, (uint)count); + } + + _handle->Position = i; + } + + /// + /// Write + /// + /// Buffer + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Write(ReadOnlySpan buffer) + { + EnsureNotClosed(); + var i = _handle->Position + buffer.Length; + if (i < 0) + throw new IOException("IO_StreamTooLong"); + if (i > _handle->Length) + { + var mustZero = _handle->Position > _handle->Length; + if (i > _handle->Capacity) + { + var allocatedNewArray = EnsureCapacity(i); + if (allocatedNewArray) + mustZero = false; + } + + if (mustZero) + Unsafe.InitBlock(_handle->Array + _handle->Length, 0, (uint)(i - _handle->Length)); + _handle->Length = i; + } + + Unsafe.CopyBlockUnaligned(ref *(_handle->Array + _handle->Position), ref MemoryMarshal.GetReference(buffer), (uint)buffer.Length); + _handle->Position = i; + } + + /// + /// Write + /// + /// Byte + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void WriteByte(byte value) + { + EnsureNotClosed(); + if (_handle->Position >= _handle->Length) + { + var newLength = _handle->Position + 1; + var mustZero = _handle->Position > _handle->Length; + if (newLength >= _handle->Capacity) + { + var allocatedNewArray = EnsureCapacity(newLength); + if (allocatedNewArray) + mustZero = false; + } + + if (mustZero) + Unsafe.InitBlock(_handle->Array + _handle->Length, 0, (uint)(_handle->Position - _handle->Length)); + _handle->Length = newLength; + } + + _handle->Array[_handle->Position++] = value; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// Ensured + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new IOException("IO_StreamTooLong"); + if (capacity > _handle->Capacity) + { + var newCapacity = capacity > 256 ? capacity : 256; + if (newCapacity < _handle->Capacity * 2) + newCapacity = _handle->Capacity * 2; + if ((uint)(_handle->Capacity * 2) > 2147483591) + newCapacity = capacity > 2147483591 ? capacity : 2147483591; + Capacity = newCapacity; + return true; + } + + return false; + } + + /// + /// Ensure not closed + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureNotClosed() + { + if (_handle == null) + throw new ObjectDisposedException("StreamClosed"); + } + + /// + /// Empty + /// + public static NativeMemoryStream Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryStream.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryStream.cs.meta new file mode 100644 index 00000000..1045fa24 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryStream.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bff85e1a03f9b4975812b50ae0c6f48b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryWriter.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryWriter.cs new file mode 100644 index 00000000..e5b8e201 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryWriter.cs @@ -0,0 +1,370 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native memory writer + /// + [StructLayout(LayoutKind.Sequential)] + public unsafe ref struct NativeMemoryWriter + { + /// + /// Array + /// + public readonly byte* Array; + + /// + /// Length + /// + public readonly int Length; + + /// + /// Position + /// + public int Position; + + /// + /// Structure + /// + /// Array + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMemoryWriter(byte* array, int length) + { + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), length, "MustBeNonNegative"); + Array = array; + Length = length; + Position = 0; + } + + /// + /// Remaining + /// + public int Remaining => Length - Position; + + /// + /// Get reference + /// + /// Index + public byte* this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Array + index; + } + + /// + /// Get reference + /// + /// Index + public byte* this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Array + index; + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMemoryWriter other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => throw new NotSupportedException("Cannot call Equals on NativeMemoryWriter"); + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => HashCode.Combine((int)(nint)Array, Length, Position); + + /// + /// To string + /// + /// String + public override string ToString() => "NativeMemoryWriter"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMemoryWriter left, NativeMemoryWriter right) => left.Array == right.Array && left.Length == right.Length && left.Position == right.Position; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMemoryWriter left, NativeMemoryWriter right) => left.Array != right.Array || left.Length != right.Length || left.Position != right.Position; + + /// + /// Advance + /// + /// Count + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Advance(int count) + { + var newPosition = Position + count; + if (newPosition < 0 || newPosition > Length) + throw new ArgumentOutOfRangeException(nameof(count), "Cannot advance past the end of the buffer."); + Position = newPosition; + } + + /// + /// Try advance + /// + /// Count + /// Advanced + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryAdvance(int count) + { + var newPosition = Position + count; + if (newPosition < 0 || newPosition > Length) + return false; + Position = newPosition; + return true; + } + + /// + /// Write + /// + /// object + /// Type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Write(T* obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {sizeof(T)}, but buffer length is {Remaining}."); + Unsafe.CopyBlockUnaligned(Array + Position, obj, (uint)sizeof(T)); + Position += sizeof(T); + } + + /// + /// Try write + /// + /// object + /// Type + /// Wrote + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryWrite(T* obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + return false; + Unsafe.CopyBlockUnaligned(Array + Position, obj, (uint)sizeof(T)); + Position += sizeof(T); + return true; + } + + /// + /// Write + /// + /// object + /// Count + /// Type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Write(T* obj, int count) where T : unmanaged + { + count *= sizeof(T); + if (Position + count > Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {count}, but buffer length is {Remaining}."); + Unsafe.CopyBlockUnaligned(Array + Position, obj, (uint)count); + Position += count; + } + + /// + /// Try write + /// + /// object + /// Count + /// Type + /// Wrote + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryWrite(T* obj, int count) where T : unmanaged + { + count *= sizeof(T); + if (Position + count > Length) + return false; + Unsafe.CopyBlockUnaligned(Array + Position, obj, (uint)count); + Position += count; + return true; + } + + /// + /// Write + /// + /// object + /// Type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Write(in T obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + throw new ArgumentOutOfRangeException(nameof(T), $"Requires size is {sizeof(T)}, but buffer length is {Remaining}."); + Unsafe.WriteUnaligned(Array + Position, obj); + Position += sizeof(T); + } + + /// + /// Try write + /// + /// object + /// Type + /// Wrote + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryWrite(in T obj) where T : unmanaged + { + if (Position + sizeof(T) > Length) + return false; + Unsafe.WriteUnaligned(Array + Position, obj); + Position += sizeof(T); + return true; + } + + /// + /// Write bytes + /// + /// Buffer + /// Length + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void WriteBytes(byte* buffer, int length) + { + if (Position + length > Length) + throw new ArgumentOutOfRangeException(nameof(length), $"Requires size is {length}, but buffer length is {Remaining}."); + Unsafe.CopyBlockUnaligned(Array + Position, buffer, (uint)length); + Position += length; + } + + /// + /// Try write bytes + /// + /// Buffer + /// Length + /// Wrote + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryWriteBytes(byte* buffer, int length) + { + if (Position + length > Length) + return false; + Unsafe.CopyBlockUnaligned(Array + Position, buffer, (uint)length); + Position += length; + return true; + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => Position = 0; + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() => MemoryMarshal.CreateSpan(ref *Array, Position); + + /// + /// As span + /// + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int length) => MemoryMarshal.CreateSpan(ref *Array, length); + + /// + /// As span + /// + /// Start + /// Length + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan(int start, int length) => MemoryMarshal.CreateSpan(ref *(Array + start), length); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan() => MemoryMarshal.CreateReadOnlySpan(ref *Array, Position); + + /// + /// As readOnly span + /// + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int length) => MemoryMarshal.CreateReadOnlySpan(ref *Array, length); + + /// + /// As readOnly span + /// + /// Start + /// Length + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan AsReadOnlySpan(int start, int length) => MemoryMarshal.CreateReadOnlySpan(ref *(Array + start), length); + + /// + /// As span + /// + /// Span + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator Span(NativeMemoryWriter writer) => writer.AsSpan(); + + /// + /// As readOnly span + /// + /// ReadOnlySpan + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(NativeMemoryWriter writer) => writer.AsReadOnlySpan(); + + /// + /// As native memory reader + /// + /// NativeMemoryReader + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeMemoryReader(NativeMemoryWriter writer) => new(writer.Array, writer.Position); + + /// + /// As native memory writer + /// + /// NativeMemoryWriter + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeMemoryWriter(NativeArray writer) => new(writer.Array, writer.Length); + + /// + /// As native memory writer + /// + /// NativeMemoryWriter + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeMemoryWriter(NativeMemoryArray writer) => new(writer.Array, writer.Length); + + /// + /// As native memory writer + /// + /// NativeMemoryWriter + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeMemoryWriter(NativeArraySegment writer) => new(writer.Array + writer.Offset, writer.Count); + + /// + /// Empty + /// + public static NativeMemoryWriter Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryWriter.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryWriter.cs.meta new file mode 100644 index 00000000..f250a699 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMemoryWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e7eda3c17c0ee481699b9ef814ec7d1b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMonitorLock.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMonitorLock.cs new file mode 100644 index 00000000..47bf8a5a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMonitorLock.cs @@ -0,0 +1,210 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET7_0_OR_GREATER +#endif + +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8604 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native monitorLock + /// + [StructLayout(LayoutKind.Sequential)] + public struct NativeMonitorLock : IDisposable, IEquatable + { + /// + /// Handle + /// + private GCHandle _handle; + + /// + /// Structure + /// + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMonitorLock(object value) => _handle = GCHandle.Alloc(value, GCHandleType.Normal); + + /// + /// Structure + /// + /// Value + /// GCHandle type + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeMonitorLock(object value, GCHandleType type) => _handle = GCHandle.Alloc(value, type); + + /// + /// Is created + /// + public bool IsCreated => _handle.IsAllocated; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeMonitorLock other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeMonitorLock nativeMonitorLock && nativeMonitorLock == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => "NativeMonitorLock"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeMonitorLock left, NativeMonitorLock right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeMonitorLock left, NativeMonitorLock right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (!_handle.IsAllocated) + return; + _handle.Free(); + } + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enter() => Monitor.Enter(_handle.Target); + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enter(ref bool lockTaken) => Monitor.Enter(_handle.Target, ref lockTaken); + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnter() => Monitor.TryEnter(_handle.Target); + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void TryEnter(ref bool lockTaken) => Monitor.TryEnter(_handle.Target, ref lockTaken); + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnter(int millisecondsTimeout) => Monitor.TryEnter(_handle.Target, millisecondsTimeout); + + /// + /// Enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void TryEnter(int millisecondsTimeout, ref bool lockTaken) => Monitor.TryEnter(_handle.Target, millisecondsTimeout, ref lockTaken); + + /// + /// Is entered + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsEntered() => Monitor.IsEntered(_handle.Target); + + /// + /// Wait + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Wait(int millisecondsTimeout) => Monitor.Wait(_handle.Target, millisecondsTimeout); + + /// + /// Pulse + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Pulse() => Monitor.Pulse(_handle.Target); + + /// + /// Pulse all + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void PulseAll() => Monitor.PulseAll(_handle.Target); + + /// + /// Try enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnter(TimeSpan timeout) => Monitor.TryEnter(_handle.Target, timeout); + + /// + /// Try enter + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void TryEnter(TimeSpan timeout, ref bool lockTaken) => Monitor.TryEnter(_handle.Target, timeout, ref lockTaken); + + /// + /// Wait + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Wait(TimeSpan timeout) => Monitor.Wait(_handle.Target, timeout); + + /// + /// Wait + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Wait() => Monitor.Wait(_handle.Target); + + /// + /// Wait + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Wait(int millisecondsTimeout, bool exitContext) => Monitor.Wait(_handle.Target, millisecondsTimeout, exitContext); + + /// + /// Wait + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Wait(TimeSpan timeout, bool exitContext) => Monitor.Wait(_handle.Target, timeout, exitContext); + + /// + /// Exit + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Exit() => Monitor.Exit(_handle.Target); + + /// + /// Empty + /// + public static NativeMonitorLock Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMonitorLock.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMonitorLock.cs.meta new file mode 100644 index 00000000..804fddf2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeMonitorLock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4d6cec6825324e09a10f908a882f75b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativePriorityQueue.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativePriorityQueue.cs new file mode 100644 index 00000000..da6e60d9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativePriorityQueue.cs @@ -0,0 +1,618 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native priorityQueue + /// + /// Type + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativePriorityQueue : IDisposable, IEquatable> where TElement : unmanaged where TPriority : unmanaged, IComparable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativePriorityQueueHandle + { + /// + /// Nodes + /// + public ValueTuple* Nodes; + + /// + /// Length + /// + public int Length; + + /// + /// Unordered items + /// + public UnorderedItemsCollection UnorderedItems; + + /// + /// Size + /// + public int Size; + + /// + /// Version + /// + public int Version; + } + + /// + /// Handle + /// + private readonly NativePriorityQueueHandle* _handle; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativePriorityQueue(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativePriorityQueueHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativePriorityQueueHandle)); + _handle->Nodes = (ValueTuple*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(ValueTuple))); + _handle->Length = capacity; + _handle->UnorderedItems = new UnorderedItemsCollection(this); + _handle->Size = 0; + _handle->Version = 0; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Size == 0; + + /// + /// Get reference + /// + /// Index + public (TElement Element, TPriority Priority) this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _handle->Nodes[index]; + } + + /// + /// Count + /// + public int Count => _handle->Size; + + /// + /// Unordered items + /// + public UnorderedItemsCollection UnorderedItems => _handle->UnorderedItems; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativePriorityQueue other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativePriorityQueue nativeQueue && nativeQueue == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativePriorityQueue<{typeof(TElement).Name}, {typeof(TPriority).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativePriorityQueue left, NativePriorityQueue right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativePriorityQueue left, NativePriorityQueue right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Nodes); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _handle->Size = 0; + ++_handle->Version; + } + + /// + /// Enqueue + /// + /// Element + /// Priority + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enqueue(in TElement element, in TPriority priority) + { + var size = _handle->Size; + ++_handle->Version; + if (_handle->Length == size) + Grow(size + 1); + _handle->Size = size + 1; + MoveUp(new ValueTuple(element, priority), size); + } + + /// + /// Try enqueue + /// + /// Element + /// Priority + /// Enqueued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnqueue(in TElement element, in TPriority priority) + { + var size = _handle->Size; + ++_handle->Version; + if (_handle->Length != size) + { + _handle->Size = size + 1; + MoveUp(new ValueTuple(element, priority), size); + return true; + } + + return false; + } + + /// + /// Enqueue dequeue + /// + /// Element + /// Priority + /// Element + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TElement EnqueueDequeue(in TElement element, in TPriority priority) + { + if (_handle->Size != 0) + { + var node = _handle->Nodes[0]; + if (priority.CompareTo(node.Item2) > 0) + { + MoveDown(new ValueTuple(element, priority), 0); + ++_handle->Version; + return node.Item1; + } + } + + return element; + } + + /// + /// Try enqueue dequeue + /// + /// Element + /// Priority + /// Element + /// Enqueued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnqueueDequeue(in TElement element, in TPriority priority, out TElement result) + { + if (_handle->Size != 0) + { + var node = _handle->Nodes[0]; + if (priority.CompareTo(node.Item2) > 0) + { + MoveDown(new ValueTuple(element, priority), 0); + ++_handle->Version; + result = node.Item1; + return true; + } + } + + result = element; + return false; + } + + /// + /// Dequeue + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TElement Dequeue() + { + if (_handle->Size == 0) + throw new InvalidOperationException("EmptyQueue"); + var element = _handle->Nodes[0].Item1; + RemoveRootNode(); + return element; + } + + /// + /// Try dequeue + /// + /// Element + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out TElement element) + { + if (_handle->Size != 0) + { + var tuple = _handle->Nodes[0]; + element = tuple.Item1; + RemoveRootNode(); + return true; + } + + element = default; + return false; + } + + /// + /// Try dequeue + /// + /// Element + /// Priority + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out TElement element, out TPriority priority) + { + if (_handle->Size != 0) + { + var tuple = _handle->Nodes[0]; + element = tuple.Item1; + priority = tuple.Item2; + RemoveRootNode(); + return true; + } + + element = default; + priority = default; + return false; + } + + /// + /// Dequeue enqueue + /// + /// Element + /// Priority + /// Element + public TElement DequeueEnqueue(in TElement element, in TPriority priority) + { + if (_handle->Size == 0) + throw new InvalidOperationException("EmptyQueue"); + var node = _handle->Nodes[0]; + if (priority.CompareTo(node.Item2) > 0) + MoveDown(new ValueTuple(element, priority), 0); + else + _handle->Nodes[0] = new ValueTuple(element, priority); + ++_handle->Version; + return node.Item1; + } + + /// + /// Try dequeue enqueue + /// + /// Element + /// Priority + /// Element + /// Dequeued + public bool TryDequeueEnqueue(in TElement element, in TPriority priority, out TElement result) + { + if (_handle->Size == 0) + { + result = default; + return false; + } + + var node = _handle->Nodes[0]; + if (priority.CompareTo(node.Item2) > 0) + MoveDown(new ValueTuple(element, priority), 0); + else + _handle->Nodes[0] = new ValueTuple(element, priority); + ++_handle->Version; + result = node.Item1; + return true; + } + + /// + /// Peek + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TElement Peek() => _handle->Size == 0 ? throw new InvalidOperationException("EmptyQueue") : _handle->Nodes[0].Item1; + + /// + /// Try peek + /// + /// Element + /// Priority + /// Peeked + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPeek(out TElement element, out TPriority priority) + { + if (_handle->Size != 0) + { + var tuple = _handle->Nodes[0]; + element = tuple.Item1; + priority = tuple.Item2; + return true; + } + + element = default; + priority = default; + return false; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (_handle->Length < capacity) + { + Grow(capacity); + ++_handle->Version; + } + + return _handle->Length; + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void TrimExcess() + { + if (_handle->Size >= (int)(_handle->Length * 0.9)) + return; + var nodes = (ValueTuple*)NativeMemoryAllocator.Alloc((uint)(_handle->Size * sizeof(ValueTuple))); + Unsafe.CopyBlockUnaligned(nodes, _handle->Nodes, (uint)_handle->Size); + NativeMemoryAllocator.Free(_handle->Nodes); + _handle->Nodes = nodes; + _handle->Length = _handle->Size; + ++_handle->Version; + } + + /// + /// Grow + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Grow(int capacity) + { + var newCapacity = 2 * _handle->Length; + if ((uint)newCapacity > 2147483591) + newCapacity = 2147483591; + var expected = _handle->Length + 4; + newCapacity = newCapacity > expected ? newCapacity : expected; + if (newCapacity < capacity) + newCapacity = capacity; + var nodes = (ValueTuple*)NativeMemoryAllocator.Alloc((uint)(newCapacity * sizeof(ValueTuple))); + Unsafe.CopyBlockUnaligned(nodes, _handle->Nodes, (uint)_handle->Size); + NativeMemoryAllocator.Free(_handle->Nodes); + _handle->Nodes = nodes; + _handle->Length = newCapacity; + } + + /// + /// Remove root node + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void RemoveRootNode() + { + var index = --_handle->Size; + ++_handle->Version; + if (index > 0) + { + var node = _handle->Nodes[index]; + MoveDown(node, 0); + } + } + + /// + /// Move up + /// + /// Node + /// Node index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void MoveUp(in ValueTuple node, int nodeIndex) + { + var nodes = _handle->Nodes; + int parentIndex; + for (; nodeIndex > 0; nodeIndex = parentIndex) + { + parentIndex = (nodeIndex - 1) >> 2; + var tuple = nodes[parentIndex]; + if (node.Item2.CompareTo(tuple.Item2) < 0) + nodes[nodeIndex] = tuple; + else + break; + } + + nodes[nodeIndex] = node; + } + + /// + /// Move down + /// + /// Node + /// Node index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void MoveDown(in ValueTuple node, int nodeIndex) + { + var nodes = _handle->Nodes; + int firstChildIndex; + int first; + for (var size = _handle->Size; (firstChildIndex = (nodeIndex << 2) + 1) < size; nodeIndex = first) + { + var valueTuple = nodes[firstChildIndex]; + first = firstChildIndex; + var minSize = firstChildIndex + 4; + var second = minSize <= size ? minSize : size; + while (++firstChildIndex < second) + { + var tuple = nodes[firstChildIndex]; + if (tuple.Item2.CompareTo(valueTuple.Item2) < 0) + { + valueTuple = tuple; + first = firstChildIndex; + } + } + + if (node.Item2.CompareTo(valueTuple.Item2) > 0) + nodes[nodeIndex] = valueTuple; + else + break; + } + + nodes[nodeIndex] = node; + } + + /// + /// Empty + /// + public static NativePriorityQueue Empty => new(); + + /// + /// Unordered items collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct UnorderedItemsCollection + { + /// + /// NativePriorityQueue + /// + private readonly NativePriorityQueue _nativePriorityQueue; + + /// + /// Structure + /// + /// Native priorityQueue + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal UnorderedItemsCollection(NativePriorityQueue nativePriorityQueue) => _nativePriorityQueue = nativePriorityQueue; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativePriorityQueue); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativePriorityQueue + /// + private readonly NativePriorityQueue _nativePriorityQueue; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Index + /// + private int _index; + + /// + /// Current + /// + private ValueTuple _current; + + /// + /// Structure + /// + /// Native priorityQueue + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativePriorityQueue nativePriorityQueue) + { + _nativePriorityQueue = nativePriorityQueue; + _index = 0; + _version = nativePriorityQueue._handle->Version; + _current = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativePriorityQueue._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if ((uint)_index >= (uint)_nativePriorityQueue._handle->Size) + { + _index = _nativePriorityQueue._handle->Size + 1; + _current = default; + return false; + } + + _current = _nativePriorityQueue._handle->Nodes[_index]; + ++_index; + return true; + } + + /// + /// Current + /// + public (TElement Element, TPriority Priority) Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativePriorityQueue.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativePriorityQueue.cs.meta new file mode 100644 index 00000000..c4354940 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativePriorityQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ccbacb3413a174e6c87f2346c5423dd0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeQueue.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeQueue.cs new file mode 100644 index 00000000..689ff66c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeQueue.cs @@ -0,0 +1,455 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native queue + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeQueue : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeQueueHandle + { + /// + /// Array + /// + public T* Array; + + /// + /// Length + /// + public int Length; + + /// + /// Head + /// + public int Head; + + /// + /// Tail + /// + public int Tail; + + /// + /// Size + /// + public int Size; + + /// + /// Version + /// + public int Version; + } + + /// + /// Handle + /// + private readonly NativeQueueHandle* _handle; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeQueue(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeQueueHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeQueueHandle)); + _handle->Array = (T*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(T))); + _handle->Length = capacity; + _handle->Head = 0; + _handle->Tail = 0; + _handle->Size = 0; + _handle->Version = 0; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Size == 0; + + /// + /// Get reference + /// + /// Index + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Get reference + /// + /// Index + public ref T this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Count + /// + public int Count => _handle->Size; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeQueue other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeQueue nativeQueue && nativeQueue == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeQueue<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeQueue left, NativeQueue right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeQueue left, NativeQueue right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Array); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _handle->Size = 0; + _handle->Head = 0; + _handle->Tail = 0; + _handle->Version++; + } + + /// + /// Enqueue + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enqueue(in T item) + { + if (_handle->Size == _handle->Length) + Grow(_handle->Size + 1); + _handle->Array[_handle->Tail] = item; + MoveNext(ref _handle->Tail); + _handle->Size++; + _handle->Version++; + } + + /// + /// Try enqueue + /// + /// Item + /// Enqueued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryEnqueue(in T item) + { + if (_handle->Size != _handle->Length) + { + _handle->Array[_handle->Tail] = item; + MoveNext(ref _handle->Tail); + _handle->Size++; + _handle->Version++; + return true; + } + + return false; + } + + /// + /// Dequeue + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Dequeue() + { + if (_handle->Size == 0) + throw new InvalidOperationException("EmptyQueue"); + var removed = _handle->Array[_handle->Head]; + MoveNext(ref _handle->Head); + _handle->Size--; + _handle->Version++; + return removed; + } + + /// + /// Try dequeue + /// + /// Item + /// Dequeued + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryDequeue(out T result) + { + if (_handle->Size == 0) + { + result = default; + return false; + } + + result = _handle->Array[_handle->Head]; + MoveNext(ref _handle->Head); + _handle->Size--; + _handle->Version++; + return true; + } + + /// + /// Peek + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Peek() => _handle->Size == 0 ? throw new InvalidOperationException("EmptyQueue") : _handle->Array[_handle->Head]; + + /// + /// Try peek + /// + /// Item + /// Peeked + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPeek(out T result) + { + if (_handle->Size == 0) + { + result = default; + return false; + } + + result = _handle->Array[_handle->Head]; + return true; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (_handle->Length < capacity) + Grow(capacity); + return _handle->Length; + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess() + { + var threshold = (int)(_handle->Length * 0.9); + if (_handle->Size < threshold) + SetCapacity(_handle->Size); + return _handle->Length; + } + + /// + /// Set capacity + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SetCapacity(int capacity) + { + var newArray = (T*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(T))); + if (_handle->Size > 0) + { + if (_handle->Head < _handle->Tail) + { + Unsafe.CopyBlockUnaligned(newArray, _handle->Array + _handle->Head, (uint)(_handle->Size * sizeof(T))); + } + else + { + Unsafe.CopyBlockUnaligned(newArray, _handle->Array + _handle->Head, (uint)((_handle->Length - _handle->Head) * sizeof(T))); + Unsafe.CopyBlockUnaligned(newArray + _handle->Length - _handle->Head, _handle->Array, (uint)(_handle->Tail * sizeof(T))); + } + } + + NativeMemoryAllocator.Free(_handle->Array); + _handle->Array = newArray; + _handle->Length = capacity; + _handle->Head = 0; + _handle->Tail = _handle->Size == capacity ? 0 : _handle->Size; + _handle->Version++; + } + + /// + /// Grow + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Grow(int capacity) + { + var newCapacity = 2 * _handle->Length; + if ((uint)newCapacity > 2147483591) + newCapacity = 2147483591; + var expected = _handle->Length + 4; + newCapacity = newCapacity > expected ? newCapacity : expected; + if (newCapacity < capacity) + newCapacity = capacity; + SetCapacity(newCapacity); + } + + /// + /// Move next + /// + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void MoveNext(ref int index) + { + var tmp = index + 1; + if (tmp == _handle->Length) + tmp = 0; + index = tmp; + } + + /// + /// Empty + /// + public static NativeQueue Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeQueue + /// + private readonly NativeQueue _nativeQueue; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Index + /// + private int _index; + + /// + /// Current + /// + private T _currentElement; + + /// + /// Structure + /// + /// NativeQueue + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeQueue nativeQueue) + { + _nativeQueue = nativeQueue; + _version = nativeQueue._handle->Version; + _index = -1; + _currentElement = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeQueue._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if (_index == -2) + return false; + _index++; + if (_index == _nativeQueue._handle->Size) + { + _index = -2; + _currentElement = default; + return false; + } + + var array = _nativeQueue._handle->Array; + var capacity = (uint)_nativeQueue._handle->Length; + var arrayIndex = (uint)(_nativeQueue._handle->Head + _index); + if (arrayIndex >= capacity) + arrayIndex -= capacity; + _currentElement = array[arrayIndex]; + return true; + } + + /// + /// Current + /// + public T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _index < 0 ? throw new InvalidOperationException(_index == -1 ? "EnumNotStarted" : "EnumEnded") : _currentElement; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeQueue.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeQueue.cs.meta new file mode 100644 index 00000000..4d321784 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f7979e9a0b80b48b8b5a675b18858259 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeReference.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeReference.cs new file mode 100644 index 00000000..76ffcc9f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeReference.cs @@ -0,0 +1,149 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native reference + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeReference : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Handle + /// + private readonly T* _handle; + + /// + /// Structure + /// + /// Handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeReference(T* handle) => _handle = handle; + + /// + /// Structure + /// + /// Handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeReference(nint handle) => _handle = (T*)handle; + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Handle + /// + public T* Handle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _handle; + } + + /// + /// Value + /// + public ref T Value + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref *_handle; + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeReference other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeReference nativeReference && nativeReference == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeReference<{typeof(T).Name}>"; + + /// + /// As reference + /// + /// NativeReference + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeReference(T* handle) => new(handle); + + /// + /// As handle + /// + /// Handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator T*(NativeReference nativeReference) => nativeReference._handle; + + /// + /// As reference + /// + /// NativeReference + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator NativeReference(nint handle) => new((T*)handle); + + /// + /// As handle + /// + /// Handle + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator nint(NativeReference nativeReference) => (nint)nativeReference._handle; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeReference left, NativeReference right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeReference left, NativeReference right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Empty + /// + public static NativeReference Empty => new(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeReference.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeReference.cs.meta new file mode 100644 index 00000000..5b669c4d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeReference.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 067f01b15247d473aa3f7a4b5a914b28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedDictionary.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedDictionary.cs new file mode 100644 index 00000000..42de38ca --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedDictionary.cs @@ -0,0 +1,1262 @@ +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Collections.Generic; +#endif +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET5_0_OR_GREATER +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native dictionary + /// + /// Type + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeSortedDictionary : IDisposable, IEquatable> where TKey : unmanaged, IComparable where TValue : unmanaged + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeSortedDictionaryHandle + { + /// + /// Root + /// + public Node* Root; + + /// + /// Count + /// + public int Count; + + /// + /// Version + /// + public int Version; + + /// + /// Node pool + /// + public NativeMemoryPool NodePool; + + /// + /// Keys + /// + public KeyCollection Keys; + + /// + /// Values + /// + public ValueCollection Values; + } + + /// + /// Handle + /// + private readonly NativeSortedDictionaryHandle* _handle; + + /// + /// Keys + /// + public KeyCollection Keys => _handle->Keys; + + /// + /// Values + /// + public ValueCollection Values => _handle->Values; + + /// + /// Structure + /// + /// MemoryPool size + /// MemoryPool maxFreeSlabs + public NativeSortedDictionary(int size, int maxFreeSlabs) + { + var nodePool = new NativeMemoryPool(size, sizeof(Node), maxFreeSlabs); + _handle = (NativeSortedDictionaryHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeSortedDictionaryHandle)); + _handle->Root = null; + _handle->Count = 0; + _handle->Version = 0; + _handle->NodePool = nodePool; + _handle->Keys = new KeyCollection(this); + _handle->Values = new ValueCollection(this); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Count == 0; + + /// + /// Count + /// + public int Count => _handle->Count; + + /// + /// Min + /// + public KeyValuePair? Min + { + get + { + if (_handle->Root == null) + return default; + var current = _handle->Root; + while (current->Left != null) + current = current->Left; + return new KeyValuePair(current->Key, current->Value); + } + } + + /// + /// Max + /// + public KeyValuePair? Max + { + get + { + if (_handle->Root == null) + return default; + var current = _handle->Root; + while (current->Right != null) + current = current->Right; + return new KeyValuePair(current->Key, current->Value); + } + } + + /// + /// Get or set value + /// + /// Key + public TValue this[in TKey key] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (!TryGetValue(key, out var value)) + throw new KeyNotFoundException(key.ToString()); + return value; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + var node = FindNode(key); + if (node == null) + { + Add(key, value); + } + else + { + node->Value = value; + _handle->Version++; + } + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeSortedDictionary other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeSortedDictionary nativeSortedDictionary && nativeSortedDictionary == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeSortedDictionary<{typeof(TKey).Name}, {typeof(TValue).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeSortedDictionary left, NativeSortedDictionary right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeSortedDictionary left, NativeSortedDictionary right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + _handle->NodePool.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + if (_handle->Root != null) + { + var nodeStack = new NativeStack(2 * Log2(_handle->Count + 1)); + nodeStack.Push((nint)_handle->Root); + while (nodeStack.TryPop(out var node)) + { + var currentNode = (Node*)node; + if (currentNode->Left != null) + nodeStack.Push((nint)currentNode->Left); + if (currentNode->Right != null) + nodeStack.Push((nint)currentNode->Right); + _handle->NodePool.Return(currentNode); + } + + nodeStack.Dispose(); + } + + _handle->Root = null; + _handle->Count = 0; + ++_handle->Version; + } + + /// + /// Add + /// + /// Key + /// Value + /// Added + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Add(in TKey key, in TValue value) + { + if (_handle->Root == null) + { + _handle->Root = (Node*)_handle->NodePool.Rent(); + _handle->Root->Key = key; + _handle->Root->Value = value; + _handle->Root->Left = null; + _handle->Root->Right = null; + _handle->Root->Color = NodeColor.Black; + _handle->Count = 1; + _handle->Version++; + return true; + } + + var current = _handle->Root; + Node* parent = null; + Node* grandParent = null; + Node* greatGrandParent = null; + _handle->Version++; + var order = 0; + while (current != null) + { + order = key.CompareTo(current->Key); + if (order == 0) + { + _handle->Root->ColorBlack(); + return false; + } + + if (current->Is4Node) + { + current->Split4Node(); + if (Node.IsNonNullRed(parent)) + InsertionBalance(current, parent, grandParent, greatGrandParent); + } + + greatGrandParent = grandParent; + grandParent = parent; + parent = current; + current = order < 0 ? current->Left : current->Right; + } + + var node = (Node*)_handle->NodePool.Rent(); + node->Key = key; + node->Value = value; + node->Left = null; + node->Right = null; + node->Color = NodeColor.Red; + if (order > 0) + parent->Right = node; + else + parent->Left = node; + if (parent->IsRed) + InsertionBalance(node, parent, grandParent, greatGrandParent); + _handle->Root->ColorBlack(); + ++_handle->Count; + return true; + } + + /// + /// Remove + /// + /// Key + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in TKey key) + { + if (_handle->Root == null) + return false; + _handle->Version++; + var current = _handle->Root; + Node* parent = null; + Node* grandParent = null; + Node* match = null; + Node* parentOfMatch = null; + var foundMatch = false; + while (current != null) + { + if (current->Is2Node) + { + if (parent == null) + { + current->ColorRed(); + } + else + { + var sibling = parent->GetSibling(current); + if (sibling->IsRed) + { + if (parent->Right == sibling) + parent->RotateLeft(); + else + parent->RotateRight(); + parent->ColorRed(); + sibling->ColorBlack(); + ReplaceChildOrRoot(grandParent, parent, sibling); + grandParent = sibling; + if (parent == match) + parentOfMatch = sibling; + sibling = parent->GetSibling(current); + } + + if (sibling->Is2Node) + { + parent->Merge2Nodes(); + } + else + { + var newGrandParent = parent->Rotate(parent->GetRotation(current, sibling)); + newGrandParent->Color = parent->Color; + parent->ColorBlack(); + current->ColorRed(); + ReplaceChildOrRoot(grandParent, parent, newGrandParent); + if (parent == match) + parentOfMatch = newGrandParent; + } + } + } + + var order = foundMatch ? -1 : key.CompareTo(current->Key); + if (order == 0) + { + foundMatch = true; + match = current; + parentOfMatch = parent; + } + + grandParent = parent; + parent = current; + current = order < 0 ? current->Left : current->Right; + } + + if (match != null) + { + ReplaceNode(match, parentOfMatch, parent, grandParent); + --_handle->Count; + _handle->NodePool.Return(match); + } + + if (_handle->Root != null) + _handle->Root->ColorBlack(); + return foundMatch; + } + + /// + /// Remove + /// + /// Key + /// Value + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in TKey key, out TValue value) + { + if (_handle->Root == null) + { + value = default; + return false; + } + + _handle->Version++; + var current = _handle->Root; + Node* parent = null; + Node* grandParent = null; + Node* match = null; + Node* parentOfMatch = null; + var foundMatch = false; + while (current != null) + { + if (current->Is2Node) + { + if (parent == null) + { + current->ColorRed(); + } + else + { + var sibling = parent->GetSibling(current); + if (sibling->IsRed) + { + if (parent->Right == sibling) + parent->RotateLeft(); + else + parent->RotateRight(); + parent->ColorRed(); + sibling->ColorBlack(); + ReplaceChildOrRoot(grandParent, parent, sibling); + grandParent = sibling; + if (parent == match) + parentOfMatch = sibling; + sibling = parent->GetSibling(current); + } + + if (sibling->Is2Node) + { + parent->Merge2Nodes(); + } + else + { + var newGrandParent = parent->Rotate(parent->GetRotation(current, sibling)); + newGrandParent->Color = parent->Color; + parent->ColorBlack(); + current->ColorRed(); + ReplaceChildOrRoot(grandParent, parent, newGrandParent); + if (parent == match) + parentOfMatch = newGrandParent; + } + } + } + + var order = foundMatch ? -1 : key.CompareTo(current->Key); + if (order == 0) + { + foundMatch = true; + match = current; + parentOfMatch = parent; + } + + grandParent = parent; + parent = current; + current = order < 0 ? current->Left : current->Right; + } + + if (match != null) + { + value = match->Value; + ReplaceNode(match, parentOfMatch, parent, grandParent); + --_handle->Count; + _handle->NodePool.Return(match); + } + else + { + value = default; + } + + if (_handle->Root != null) + _handle->Root->ColorBlack(); + return foundMatch; + } + + /// + /// Contains key + /// + /// Key + /// Contains key + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(in TKey key) => FindNode(key) != null; + + /// + /// Try to get the actual value + /// + /// Key + /// Value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in TKey key, out TValue value) + { + var node = FindNode(key); + if (node != null) + { + value = node->Value; + return true; + } + + value = default; + return false; + } + + /// + /// Insertion balance + /// + /// Current + /// Parent + /// Grand parent + /// GreatGrand parent + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void InsertionBalance(Node* current, Node* parent, Node* grandParent, Node* greatGrandParent) + { + var parentIsOnRight = grandParent->Right == parent; + var currentIsOnRight = parent->Right == current; + Node* newChildOfGreatGrandParent; + if (parentIsOnRight == currentIsOnRight) + newChildOfGreatGrandParent = currentIsOnRight ? grandParent->RotateLeft() : grandParent->RotateRight(); + else + newChildOfGreatGrandParent = currentIsOnRight ? grandParent->RotateLeftRight() : grandParent->RotateRightLeft(); + grandParent->ColorRed(); + newChildOfGreatGrandParent->ColorBlack(); + ReplaceChildOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent); + } + + /// + /// Replace child or root + /// + /// Parent + /// Child + /// New child + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReplaceChildOrRoot(Node* parent, Node* child, Node* newChild) + { + if (parent != null) + parent->ReplaceChild(child, newChild); + else + _handle->Root = newChild; + } + + /// + /// Replace node + /// + /// Match + /// Parent of match + /// Successor + /// Parent of successor + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReplaceNode(Node* match, Node* parentOfMatch, Node* successor, Node* parentOfSuccessor) + { + if (successor == match) + { + successor = match->Left; + } + else + { + if (successor->Right != null) + successor->Right->ColorBlack(); + if (parentOfSuccessor != match) + { + parentOfSuccessor->Left = successor->Right; + successor->Right = match->Right; + } + + successor->Left = match->Left; + } + + if (successor != null) + successor->Color = match->Color; + ReplaceChildOrRoot(parentOfMatch, match, successor); + } + + /// + /// Find node + /// + /// Key + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Node* FindNode(in TKey key) + { + var current = _handle->Root; + while (current != null) + { + var order = key.CompareTo(current->Key); + if (order == 0) + return current; + current = order < 0 ? current->Left : current->Right; + } + + return null; + } + + /// + /// Log2 + /// + /// Value + /// Log2 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Log2(int value) => BitOperationsHelpers.Log2(value); + + /// + /// Node + /// + [StructLayout(LayoutKind.Sequential)] + private struct Node + { + /// + /// Is non null red + /// + /// Node + /// Is non null red + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNonNullRed(Node* node) => node != null && node->IsRed; + + /// + /// Is null or black + /// + /// Node + /// Is null or black + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsNullOrBlack(Node* node) => node == null || node->IsBlack; + + /// + /// Key + /// + public TKey Key + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Value + /// + public TValue Value + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Left + /// + public Node* Left + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Right + /// + public Node* Right + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Color + /// + public NodeColor Color + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Is black + /// + private bool IsBlack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Color == NodeColor.Black; + } + + /// + /// Is red + /// + public bool IsRed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Color == NodeColor.Red; + } + + /// + /// Is 2 node + /// + public bool Is2Node + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => IsBlack && IsNullOrBlack(Left) && IsNullOrBlack(Right); + } + + /// + /// Is 4 node + /// + public bool Is4Node + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => IsNonNullRed(Left) && IsNonNullRed(Right); + } + + /// + /// Set color to black + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ColorBlack() => Color = NodeColor.Black; + + /// + /// Set color to red + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ColorRed() => Color = NodeColor.Red; + + /// + /// Get rotation + /// + /// Current + /// Sibling + /// Rotation + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TreeRotation GetRotation(Node* current, Node* sibling) + { + var currentIsLeftChild = Left == current; + return IsNonNullRed(sibling->Left) ? currentIsLeftChild ? TreeRotation.RightLeft : TreeRotation.Right : currentIsLeftChild ? TreeRotation.Left : TreeRotation.LeftRight; + } + + /// + /// Get sibling + /// + /// Node + /// Sibling + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* GetSibling(Node* node) => node == Left ? Right : Left; + + /// + /// Split 4 node + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Split4Node() + { + ColorRed(); + Left->ColorBlack(); + Right->ColorBlack(); + } + + /// + /// Rotate + /// + /// Rotation + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* Rotate(TreeRotation rotation) + { + Node* removeRed; + switch (rotation) + { + case TreeRotation.Right: + removeRed = Left->Left; + removeRed->ColorBlack(); + return RotateRight(); + case TreeRotation.Left: + removeRed = Right->Right; + removeRed->ColorBlack(); + return RotateLeft(); + case TreeRotation.RightLeft: + return RotateRightLeft(); + case TreeRotation.LeftRight: + return RotateLeftRight(); + default: + return null; + } + } + + /// + /// Rotate left + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateLeft() + { + var child = Right; + Right = child->Left; + child->Left = (Node*)Unsafe.AsPointer(ref this); + return child; + } + + /// + /// Rotate left right + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateLeftRight() + { + var child = Left; + var grandChild = child->Right; + Left = grandChild->Right; + grandChild->Right = (Node*)Unsafe.AsPointer(ref this); + child->Right = grandChild->Left; + grandChild->Left = child; + return grandChild; + } + + /// + /// Rotate right + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateRight() + { + var child = Left; + Left = child->Right; + child->Right = (Node*)Unsafe.AsPointer(ref this); + return child; + } + + /// + /// Rotate right left + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateRightLeft() + { + var child = Right; + var grandChild = child->Left; + Right = grandChild->Left; + grandChild->Left = (Node*)Unsafe.AsPointer(ref this); + child->Left = grandChild->Right; + grandChild->Right = child; + return grandChild; + } + + /// + /// Merge 2 nodes + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Merge2Nodes() + { + ColorBlack(); + Left->ColorRed(); + Right->ColorRed(); + } + + /// + /// Replace child + /// + /// Child + /// New child + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ReplaceChild(Node* child, Node* newChild) + { + if (Left == child) + Left = newChild; + else + Right = newChild; + } + } + + /// + /// Empty + /// + public static NativeSortedDictionary Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator : IDisposable + { + /// + /// NativeHashSet + /// + private readonly NativeSortedDictionary _nativeSortedDictionary; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Node stack + /// + private readonly NativeStack _nodeStack; + + /// + /// Current + /// + private Node* _currentNode; + + /// + /// Current + /// + private KeyValuePair _current; + + /// + /// Structure + /// + /// NativeSortedDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedDictionary nativeSortedDictionary) + { + _nativeSortedDictionary = nativeSortedDictionary; + _version = nativeSortedDictionary._handle->Version; + _nodeStack = new NativeStack(2 * Log2(nativeSortedDictionary.Count + 1)); + _currentNode = null; + _current = default; + var node = _nativeSortedDictionary._handle->Root; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedDictionary._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if (!_nodeStack.TryPop(out var result)) + { + _currentNode = null; + _current = default; + return false; + } + + _currentNode = (Node*)result; + _current = new KeyValuePair(_currentNode->Key, _currentNode->Value); + var node = _currentNode->Right; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + + return true; + } + + /// + /// Current + /// + public KeyValuePair Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _nodeStack.Dispose(); + } + + /// + /// Key collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct KeyCollection + { + /// + /// NativeSortedDictionary + /// + private readonly NativeSortedDictionary _nativeSortedDictionary; + + /// + /// Structure + /// + /// NativeSortedDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal KeyCollection(NativeSortedDictionary nativeSortedDictionary) => _nativeSortedDictionary = nativeSortedDictionary; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeSortedDictionary); + + /// + /// Enumerator + /// + public struct Enumerator : IDisposable + { + /// + /// NativeHashSet + /// + private readonly NativeSortedDictionary _nativeSortedDictionary; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Node stack + /// + private readonly NativeStack _nodeStack; + + /// + /// Current + /// + private Node* _currentNode; + + /// + /// Current + /// + private TKey _current; + + /// + /// Structure + /// + /// NativeSortedDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedDictionary nativeSortedDictionary) + { + _nativeSortedDictionary = nativeSortedDictionary; + _version = nativeSortedDictionary._handle->Version; + _nodeStack = new NativeStack(2 * Log2(nativeSortedDictionary.Count + 1)); + _currentNode = null; + _current = default; + var node = _nativeSortedDictionary._handle->Root; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedDictionary._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if (!_nodeStack.TryPop(out var result)) + { + _currentNode = null; + _current = default; + return false; + } + + _currentNode = (Node*)result; + _current = _currentNode->Key; + var node = _currentNode->Right; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + + return true; + } + + /// + /// Current + /// + public TKey Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _nodeStack.Dispose(); + } + } + + /// + /// Value collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct ValueCollection + { + /// + /// NativeSortedDictionary + /// + private readonly NativeSortedDictionary _nativeSortedDictionary; + + /// + /// Structure + /// + /// NativeSortedDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ValueCollection(NativeSortedDictionary nativeSortedDictionary) => _nativeSortedDictionary = nativeSortedDictionary; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeSortedDictionary); + + /// + /// Enumerator + /// + public struct Enumerator : IDisposable + { + /// + /// NativeHashSet + /// + private readonly NativeSortedDictionary _nativeSortedDictionary; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Node stack + /// + private readonly NativeStack _nodeStack; + + /// + /// Current + /// + private Node* _currentNode; + + /// + /// Current + /// + private TValue _current; + + /// + /// Structure + /// + /// NativeSortedDictionary + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedDictionary nativeSortedDictionary) + { + _nativeSortedDictionary = nativeSortedDictionary; + _version = nativeSortedDictionary._handle->Version; + _nodeStack = new NativeStack(2 * Log2(nativeSortedDictionary.Count + 1)); + _currentNode = null; + _current = default; + var node = _nativeSortedDictionary._handle->Root; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedDictionary._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if (!_nodeStack.TryPop(out var result)) + { + _currentNode = null; + _current = default; + return false; + } + + _currentNode = (Node*)result; + _current = _currentNode->Value; + var node = _currentNode->Right; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + + return true; + } + + /// + /// Current + /// + public TValue Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _nodeStack.Dispose(); + } + } + + /// + /// Node color + /// + private enum NodeColor : byte + { + Black, + Red + } + + /// + /// Tree rotation + /// + private enum TreeRotation : byte + { + Left, + LeftRight, + Right, + RightLeft + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedDictionary.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedDictionary.cs.meta new file mode 100644 index 00000000..e6300725 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e295fbed2bc7842ba87143548bacc159 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedList.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedList.cs new file mode 100644 index 00000000..bb43bbf3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedList.cs @@ -0,0 +1,695 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Collections.Generic; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native sortedList + /// + /// Type + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeSortedList where TKey : unmanaged, IComparable where TValue : unmanaged + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeSortedListHandle + { + /// + /// Keys + /// + public TKey* Buckets; + + /// + /// Values + /// + public TValue* Entries; + + /// + /// Size + /// + public int Size; + + /// + /// Version + /// + public int Version; + + /// + /// Capacity + /// + public int Capacity; + + /// + /// Keys + /// + public KeyCollection Keys; + + /// + /// Values + /// + public ValueCollection Values; + } + + /// + /// Handle + /// + private readonly NativeSortedListHandle* _handle; + + /// + /// Keys + /// + public KeyCollection Keys => _handle->Keys; + + /// + /// Values + /// + public ValueCollection Values => _handle->Values; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeSortedList(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeSortedListHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeSortedListHandle)); + _handle->Buckets = (TKey*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(TKey))); + _handle->Entries = (TValue*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(TValue))); + _handle->Size = 0; + _handle->Version = 0; + _handle->Capacity = capacity; + _handle->Keys = new KeyCollection(this); + _handle->Values = new ValueCollection(this); + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Size == 0; + + /// + /// Get or set value + /// + /// Key + public TValue this[TKey key] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + var index = BinarySearch(_handle->Buckets, _handle->Size, key); + return index >= 0 ? _handle->Entries[index] : throw new KeyNotFoundException(key.ToString()); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + var index = BinarySearch(_handle->Buckets, _handle->Size, key); + if (index >= 0) + { + _handle->Entries[index] = value; + ++_handle->Version; + } + else + { + Insert(~index, key, value); + } + } + } + + /// + /// Count + /// + public int Count => _handle->Size; + + /// + /// Capacity + /// + public int Capacity + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _handle->Capacity; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + if (value < _handle->Size) + throw new ArgumentOutOfRangeException(nameof(value), value, "SmallCapacity"); + if (value != _handle->Capacity) + { + if (value > 0) + { + var keys = (TKey*)NativeMemoryAllocator.Alloc((uint)(value * sizeof(TKey))); + var values = (TValue*)NativeMemoryAllocator.Alloc((uint)(value * sizeof(TValue))); + if (_handle->Size > 0) + { + Unsafe.CopyBlockUnaligned(keys, _handle->Buckets, (uint)(_handle->Size * sizeof(TKey))); + Unsafe.CopyBlockUnaligned(values, _handle->Entries, (uint)(_handle->Size * sizeof(TValue))); + } + + NativeMemoryAllocator.Free(_handle->Buckets); + NativeMemoryAllocator.Free(_handle->Entries); + _handle->Buckets = keys; + _handle->Entries = values; + } + else + { + NativeMemoryAllocator.Free(_handle->Buckets); + NativeMemoryAllocator.Free(_handle->Entries); + _handle->Buckets = (TKey*)NativeMemoryAllocator.Alloc(0); + _handle->Entries = (TValue*)NativeMemoryAllocator.Alloc(0); + } + + _handle->Capacity = value; + } + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeSortedList other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeSortedList nativeSortedList && nativeSortedList == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeSortedList<{typeof(TKey).Name}, {typeof(TValue).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeSortedList left, NativeSortedList right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeSortedList left, NativeSortedList right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Buckets); + NativeMemoryAllocator.Free(_handle->Entries); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + ++_handle->Version; + _handle->Size = 0; + } + + /// + /// Add + /// + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(in TKey key, in TValue value) + { + var num = BinarySearch(_handle->Buckets, _handle->Size, key); + if (num >= 0) + throw new ArgumentException($"AddingDuplicate, {key}", nameof(key)); + Insert(~num, key, value); + } + + /// + /// Remove + /// + /// Key + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in TKey key) + { + var index = BinarySearch(_handle->Buckets, _handle->Size, key); + if (index >= 0) + { + --_handle->Size; + if (index < _handle->Size) + { + Unsafe.CopyBlockUnaligned(_handle->Buckets + index, _handle->Buckets + index + 1, (uint)((_handle->Size - index) * sizeof(TKey))); + Unsafe.CopyBlockUnaligned(_handle->Entries + index, _handle->Entries + index + 1, (uint)((_handle->Size - index) * sizeof(TValue))); + } + + ++_handle->Version; + return true; + } + + return false; + } + + /// + /// Remove + /// + /// Key + /// Value + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in TKey key, out TValue value) + { + var index = BinarySearch(_handle->Buckets, _handle->Size, key); + if (index >= 0) + { + value = _handle->Entries[index]; + --_handle->Size; + if (index < _handle->Size) + { + Unsafe.CopyBlockUnaligned(_handle->Buckets + index, _handle->Buckets + index + 1, (uint)((_handle->Size - index) * sizeof(TKey))); + Unsafe.CopyBlockUnaligned(_handle->Entries + index, _handle->Entries + index + 1, (uint)((_handle->Size - index) * sizeof(TValue))); + } + + ++_handle->Version; + return true; + } + + value = default; + return false; + } + + /// + /// Contains key + /// + /// Key + /// Contains key + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(in TKey key) => BinarySearch(_handle->Buckets, _handle->Size, key) >= 0; + + /// + /// Try to get the value + /// + /// Key + /// Value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in TKey key, out TValue value) + { + var index = BinarySearch(_handle->Buckets, _handle->Size, key); + if (index >= 0) + { + value = _handle->Entries[index]; + return true; + } + + value = default; + return false; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void EnsureCapacity(int capacity) + { + if (_handle->Capacity < capacity) + { + var newCapacity = 2 * _handle->Capacity; + if ((uint)newCapacity > 2147483591) + newCapacity = 2147483591; + var expected = _handle->Capacity + 4; + newCapacity = newCapacity > expected ? newCapacity : expected; + if (newCapacity < capacity) + newCapacity = capacity; + Capacity = newCapacity; + } + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess() + { + var threshold = (int)(_handle->Capacity * 0.9); + if (_handle->Size < threshold) + Capacity = _handle->Size; + return _handle->Capacity; + } + + /// + /// Insert + /// + /// Index + /// Key + /// Value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Insert(int index, in TKey key, in TValue value) + { + if (_handle->Size == _handle->Capacity) + EnsureCapacity(_handle->Size + 1); + if (index < _handle->Size) + { + Unsafe.CopyBlockUnaligned(_handle->Buckets + index + 1, _handle->Buckets + index, (uint)((_handle->Size - index) * sizeof(TKey))); + Unsafe.CopyBlockUnaligned(_handle->Entries + index + 1, _handle->Entries + index, (uint)((_handle->Size - index) * sizeof(TValue))); + } + + _handle->Buckets[index] = key; + _handle->Entries[index] = value; + ++_handle->Size; + ++_handle->Version; + } + + /// + /// Binary search + /// + /// Start + /// Length + /// Comparable + /// Index + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int BinarySearch(TKey* start, int length, in TKey comparable) + { + var low = 0; + var high = length - 1; + while (low <= high) + { + var i = (int)(((uint)high + (uint)low) >> 1); + var c = comparable.CompareTo(*(start + i)); + if (c == 0) + return i; + if (c > 0) + low = i + 1; + else + high = i - 1; + } + + return ~low; + } + + /// + /// Empty + /// + public static NativeSortedList Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeSortedList + /// + private readonly NativeSortedList _nativeSortedList; + + /// + /// Current + /// + private KeyValuePair _current; + + /// + /// Index + /// + private int _index; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Structure + /// + /// NativeSortedList + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedList nativeSortedList) + { + _nativeSortedList = nativeSortedList; + _current = default; + _index = 0; + _version = _nativeSortedList._handle->Version; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedList._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if ((uint)_index < (uint)_nativeSortedList._handle->Size) + { + _current = new KeyValuePair(_nativeSortedList._handle->Buckets[_index], _nativeSortedList._handle->Entries[_index]); + ++_index; + return true; + } + + _index = _nativeSortedList._handle->Size + 1; + return false; + } + + /// + /// Current + /// + public KeyValuePair Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + + /// + /// Key collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct KeyCollection + { + /// + /// NativeSortedList + /// + private readonly NativeSortedList _nativeSortedList; + + /// + /// Structure + /// + /// NativeSortedList + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal KeyCollection(NativeSortedList nativeSortedList) => _nativeSortedList = nativeSortedList; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeSortedList); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeSortedList + /// + private readonly NativeSortedList _nativeSortedList; + + /// + /// Current + /// + private TKey _current; + + /// + /// Index + /// + private int _index; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Structure + /// + /// NativeSortedList + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedList nativeSortedList) + { + _nativeSortedList = nativeSortedList; + _current = default; + _index = 0; + _version = _nativeSortedList._handle->Version; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedList._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if ((uint)_index < (uint)_nativeSortedList._handle->Size) + { + _current = _nativeSortedList._handle->Buckets[_index]; + ++_index; + return true; + } + + _index = _nativeSortedList._handle->Size + 1; + return false; + } + + /// + /// Current + /// + public TKey Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } + + /// + /// Value collection + /// + [StructLayout(LayoutKind.Sequential)] + public readonly struct ValueCollection + { + /// + /// NativeSortedList + /// + private readonly NativeSortedList _nativeSortedList; + + /// + /// Structure + /// + /// NativeSortedList + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ValueCollection(NativeSortedList nativeSortedList) => _nativeSortedList = nativeSortedList; + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(_nativeSortedList); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeSortedList + /// + private readonly NativeSortedList _nativeSortedList; + + /// + /// Current + /// + private TValue _current; + + /// + /// Index + /// + private int _index; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Structure + /// + /// NativeSortedList + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedList nativeSortedList) + { + _nativeSortedList = nativeSortedList; + _current = default; + _index = 0; + _version = _nativeSortedList._handle->Version; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedList._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if ((uint)_index < (uint)_nativeSortedList._handle->Size) + { + _current = _nativeSortedList._handle->Entries[_index]; + ++_index; + return true; + } + + _index = _nativeSortedList._handle->Size + 1; + return false; + } + + /// + /// Current + /// + public TValue Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedList.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedList.cs.meta new file mode 100644 index 00000000..dc022ff1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d099ab61a6bc1402d9b93681aa02480b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedSet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedSet.cs new file mode 100644 index 00000000..f3392768 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedSet.cs @@ -0,0 +1,973 @@ +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET5_0_OR_GREATER +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native sortedSet + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeSortedSet : IDisposable, IEquatable> where T : unmanaged, IComparable + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeSortedSetHandle + { + /// + /// Root + /// + public Node* Root; + + /// + /// Count + /// + public int Count; + + /// + /// Version + /// + public int Version; + + /// + /// Node pool + /// + public NativeMemoryPool NodePool; + } + + /// + /// Handle + /// + private readonly NativeSortedSetHandle* _handle; + + /// + /// Structure + /// + /// MemoryPool size + /// MemoryPool maxFreeSlabs + public NativeSortedSet(int size, int maxFreeSlabs) + { + var nodePool = new NativeMemoryPool(size, sizeof(Node), maxFreeSlabs); + _handle = (NativeSortedSetHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeSortedSetHandle)); + _handle->Root = null; + _handle->Count = 0; + _handle->Version = 0; + _handle->NodePool = nodePool; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Count == 0; + + /// + /// Count + /// + public int Count => _handle->Count; + + /// + /// Min + /// + public T? Min + { + get + { + if (_handle->Root == null) + return default; + var current = _handle->Root; + while (current->Left != null) + current = current->Left; + return current->Item; + } + } + + /// + /// Max + /// + public T? Max + { + get + { + if (_handle->Root == null) + return default; + var current = _handle->Root; + while (current->Right != null) + current = current->Right; + return current->Item; + } + } + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeSortedSet other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeSortedSet nativeSortedSet && nativeSortedSet == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeSortedSet<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeSortedSet left, NativeSortedSet right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeSortedSet left, NativeSortedSet right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + _handle->NodePool.Dispose(); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + if (_handle->Root != null) + { + var nodeStack = new NativeStack(2 * Log2(_handle->Count + 1)); + nodeStack.Push((nint)_handle->Root); + while (nodeStack.TryPop(out var node)) + { + var currentNode = (Node*)node; + if (currentNode->Left != null) + nodeStack.Push((nint)currentNode->Left); + if (currentNode->Right != null) + nodeStack.Push((nint)currentNode->Right); + _handle->NodePool.Return(currentNode); + } + + nodeStack.Dispose(); + } + + _handle->Root = null; + _handle->Count = 0; + ++_handle->Version; + } + + /// + /// Add + /// + /// Item + /// Added + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Add(in T item) + { + if (_handle->Root == null) + { + _handle->Root = (Node*)_handle->NodePool.Rent(); + _handle->Root->Item = item; + _handle->Root->Left = null; + _handle->Root->Right = null; + _handle->Root->Color = NodeColor.Black; + _handle->Count = 1; + _handle->Version++; + return true; + } + + var current = _handle->Root; + Node* parent = null; + Node* grandParent = null; + Node* greatGrandParent = null; + _handle->Version++; + var order = 0; + while (current != null) + { + order = item.CompareTo(current->Item); + if (order == 0) + { + _handle->Root->ColorBlack(); + return false; + } + + if (current->Is4Node) + { + current->Split4Node(); + if (Node.IsNonNullRed(parent)) + InsertionBalance(current, parent, grandParent, greatGrandParent); + } + + greatGrandParent = grandParent; + grandParent = parent; + parent = current; + current = order < 0 ? current->Left : current->Right; + } + + var node = (Node*)_handle->NodePool.Rent(); + node->Item = item; + node->Left = null; + node->Right = null; + node->Color = NodeColor.Red; + if (order > 0) + parent->Right = node; + else + parent->Left = node; + if (parent->IsRed) + InsertionBalance(node, parent, grandParent, greatGrandParent); + _handle->Root->ColorBlack(); + ++_handle->Count; + return true; + } + + /// + /// Add + /// + /// Equal value + /// Actual value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(in T equalValue, in T actualValue) + { + var node = FindNode(equalValue); + if (node == null) + { + Add(actualValue); + } + else + { + node->Item = actualValue; + _handle->Version++; + } + } + + /// + /// Remove + /// + /// Item + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in T item) + { + if (_handle->Root == null) + return false; + _handle->Version++; + var current = _handle->Root; + Node* parent = null; + Node* grandParent = null; + Node* match = null; + Node* parentOfMatch = null; + var foundMatch = false; + while (current != null) + { + if (current->Is2Node) + { + if (parent == null) + { + current->ColorRed(); + } + else + { + var sibling = parent->GetSibling(current); + if (sibling->IsRed) + { + if (parent->Right == sibling) + parent->RotateLeft(); + else + parent->RotateRight(); + parent->ColorRed(); + sibling->ColorBlack(); + ReplaceChildOrRoot(grandParent, parent, sibling); + grandParent = sibling; + if (parent == match) + parentOfMatch = sibling; + sibling = parent->GetSibling(current); + } + + if (sibling->Is2Node) + { + parent->Merge2Nodes(); + } + else + { + var newGrandParent = parent->Rotate(parent->GetRotation(current, sibling)); + newGrandParent->Color = parent->Color; + parent->ColorBlack(); + current->ColorRed(); + ReplaceChildOrRoot(grandParent, parent, newGrandParent); + if (parent == match) + parentOfMatch = newGrandParent; + } + } + } + + var order = foundMatch ? -1 : item.CompareTo(current->Item); + if (order == 0) + { + foundMatch = true; + match = current; + parentOfMatch = parent; + } + + grandParent = parent; + parent = current; + current = order < 0 ? current->Left : current->Right; + } + + if (match != null) + { + ReplaceNode(match, parentOfMatch, parent, grandParent); + --_handle->Count; + _handle->NodePool.Return(match); + } + + if (_handle->Root != null) + _handle->Root->ColorBlack(); + return foundMatch; + } + + /// + /// Remove + /// + /// Equal value + /// Actual value + /// Removed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(in T equalValue, out T actualValue) + { + if (_handle->Root == null) + { + actualValue = default; + return false; + } + + _handle->Version++; + var current = _handle->Root; + Node* parent = null; + Node* grandParent = null; + Node* match = null; + Node* parentOfMatch = null; + var foundMatch = false; + while (current != null) + { + if (current->Is2Node) + { + if (parent == null) + { + current->ColorRed(); + } + else + { + var sibling = parent->GetSibling(current); + if (sibling->IsRed) + { + if (parent->Right == sibling) + parent->RotateLeft(); + else + parent->RotateRight(); + parent->ColorRed(); + sibling->ColorBlack(); + ReplaceChildOrRoot(grandParent, parent, sibling); + grandParent = sibling; + if (parent == match) + parentOfMatch = sibling; + sibling = parent->GetSibling(current); + } + + if (sibling->Is2Node) + { + parent->Merge2Nodes(); + } + else + { + var newGrandParent = parent->Rotate(parent->GetRotation(current, sibling)); + newGrandParent->Color = parent->Color; + parent->ColorBlack(); + current->ColorRed(); + ReplaceChildOrRoot(grandParent, parent, newGrandParent); + if (parent == match) + parentOfMatch = newGrandParent; + } + } + } + + var order = foundMatch ? -1 : equalValue.CompareTo(current->Item); + if (order == 0) + { + foundMatch = true; + match = current; + parentOfMatch = parent; + } + + grandParent = parent; + parent = current; + current = order < 0 ? current->Left : current->Right; + } + + if (match != null) + { + actualValue = match->Item; + ReplaceNode(match, parentOfMatch, parent, grandParent); + --_handle->Count; + _handle->NodePool.Return(match); + } + else + { + actualValue = default; + } + + if (_handle->Root != null) + _handle->Root->ColorBlack(); + return foundMatch; + } + + /// + /// Contains + /// + /// Item + /// Contains + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(in T item) => FindNode(item) != null; + + /// + /// Try to get the actual value + /// + /// Equal value + /// Actual value + /// Got + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(in T equalValue, out T actualValue) + { + var node = FindNode(equalValue); + if (node != null) + { + actualValue = node->Item; + return true; + } + + actualValue = default; + return false; + } + + /// + /// Insertion balance + /// + /// Current + /// Parent + /// Grand parent + /// GreatGrand parent + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void InsertionBalance(Node* current, Node* parent, Node* grandParent, Node* greatGrandParent) + { + var parentIsOnRight = grandParent->Right == parent; + var currentIsOnRight = parent->Right == current; + Node* newChildOfGreatGrandParent; + if (parentIsOnRight == currentIsOnRight) + newChildOfGreatGrandParent = currentIsOnRight ? grandParent->RotateLeft() : grandParent->RotateRight(); + else + newChildOfGreatGrandParent = currentIsOnRight ? grandParent->RotateLeftRight() : grandParent->RotateRightLeft(); + grandParent->ColorRed(); + newChildOfGreatGrandParent->ColorBlack(); + ReplaceChildOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent); + } + + /// + /// Replace child or root + /// + /// Parent + /// Child + /// New child + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReplaceChildOrRoot(Node* parent, Node* child, Node* newChild) + { + if (parent != null) + parent->ReplaceChild(child, newChild); + else + _handle->Root = newChild; + } + + /// + /// Replace node + /// + /// Match + /// Parent of match + /// Successor + /// Parent of successor + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReplaceNode(Node* match, Node* parentOfMatch, Node* successor, Node* parentOfSuccessor) + { + if (successor == match) + { + successor = match->Left; + } + else + { + if (successor->Right != null) + successor->Right->ColorBlack(); + if (parentOfSuccessor != match) + { + parentOfSuccessor->Left = successor->Right; + successor->Right = match->Right; + } + + successor->Left = match->Left; + } + + if (successor != null) + successor->Color = match->Color; + ReplaceChildOrRoot(parentOfMatch, match, successor); + } + + /// + /// Find node + /// + /// Item + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Node* FindNode(in T item) + { + var current = _handle->Root; + while (current != null) + { + var order = item.CompareTo(current->Item); + if (order == 0) + return current; + current = order < 0 ? current->Left : current->Right; + } + + return null; + } + + /// + /// Log2 + /// + /// Value + /// Log2 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Log2(int value) => BitOperationsHelpers.Log2(value); + + /// + /// Node + /// + [StructLayout(LayoutKind.Sequential)] + private struct Node + { + /// + /// Is non null red + /// + /// Node + /// Is non null red + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNonNullRed(Node* node) => node != null && node->IsRed; + + /// + /// Is null or black + /// + /// Node + /// Is null or black + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsNullOrBlack(Node* node) => node == null || node->IsBlack; + + /// + /// Item + /// + public T Item + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Left + /// + public Node* Left + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Right + /// + public Node* Right + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Color + /// + public NodeColor Color + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set; + } + + /// + /// Is black + /// + private bool IsBlack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Color == NodeColor.Black; + } + + /// + /// Is red + /// + public bool IsRed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Color == NodeColor.Red; + } + + /// + /// Is 2 node + /// + public bool Is2Node + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => IsBlack && IsNullOrBlack(Left) && IsNullOrBlack(Right); + } + + /// + /// Is 4 node + /// + public bool Is4Node + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => IsNonNullRed(Left) && IsNonNullRed(Right); + } + + /// + /// Set color to black + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ColorBlack() => Color = NodeColor.Black; + + /// + /// Set color to red + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ColorRed() => Color = NodeColor.Red; + + /// + /// Get rotation + /// + /// Current + /// Sibling + /// Rotation + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TreeRotation GetRotation(Node* current, Node* sibling) + { + var currentIsLeftChild = Left == current; + return IsNonNullRed(sibling->Left) ? currentIsLeftChild ? TreeRotation.RightLeft : TreeRotation.Right : currentIsLeftChild ? TreeRotation.Left : TreeRotation.LeftRight; + } + + /// + /// Get sibling + /// + /// Node + /// Sibling + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* GetSibling(Node* node) => node == Left ? Right : Left; + + /// + /// Split 4 node + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Split4Node() + { + ColorRed(); + Left->ColorBlack(); + Right->ColorBlack(); + } + + /// + /// Rotate + /// + /// Rotation + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* Rotate(TreeRotation rotation) + { + Node* removeRed; + switch (rotation) + { + case TreeRotation.Right: + removeRed = Left->Left; + removeRed->ColorBlack(); + return RotateRight(); + case TreeRotation.Left: + removeRed = Right->Right; + removeRed->ColorBlack(); + return RotateLeft(); + case TreeRotation.RightLeft: + return RotateRightLeft(); + case TreeRotation.LeftRight: + return RotateLeftRight(); + default: + return null; + } + } + + /// + /// Rotate left + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateLeft() + { + var child = Right; + Right = child->Left; + child->Left = (Node*)Unsafe.AsPointer(ref this); + return child; + } + + /// + /// Rotate left right + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateLeftRight() + { + var child = Left; + var grandChild = child->Right; + Left = grandChild->Right; + grandChild->Right = (Node*)Unsafe.AsPointer(ref this); + child->Right = grandChild->Left; + grandChild->Left = child; + return grandChild; + } + + /// + /// Rotate right + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateRight() + { + var child = Left; + Left = child->Right; + child->Right = (Node*)Unsafe.AsPointer(ref this); + return child; + } + + /// + /// Rotate right left + /// + /// Node + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Node* RotateRightLeft() + { + var child = Right; + var grandChild = child->Left; + Right = grandChild->Left; + grandChild->Left = (Node*)Unsafe.AsPointer(ref this); + child->Left = grandChild->Right; + grandChild->Right = child; + return grandChild; + } + + /// + /// Merge 2 nodes + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Merge2Nodes() + { + ColorBlack(); + Left->ColorRed(); + Right->ColorRed(); + } + + /// + /// Replace child + /// + /// Child + /// New child + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ReplaceChild(Node* child, Node* newChild) + { + if (Left == child) + Left = newChild; + else + Right = newChild; + } + } + + /// + /// Empty + /// + public static NativeSortedSet Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator : IDisposable + { + /// + /// NativeHashSet + /// + private readonly NativeSortedSet _nativeSortedSet; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Node stack + /// + private readonly NativeStack _nodeStack; + + /// + /// Current + /// + private Node* _currentNode; + + /// + /// Current + /// + private T _current; + + /// + /// Structure + /// + /// NativeSortedSet + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(NativeSortedSet nativeSortedSet) + { + _nativeSortedSet = nativeSortedSet; + _version = nativeSortedSet._handle->Version; + _nodeStack = new NativeStack(2 * Log2(nativeSortedSet.Count + 1)); + _currentNode = null; + _current = default; + var node = _nativeSortedSet._handle->Root; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeSortedSet._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + if (!_nodeStack.TryPop(out var result)) + { + _currentNode = null; + _current = default; + return false; + } + + _currentNode = (Node*)result; + _current = _currentNode->Item; + var node = _currentNode->Right; + while (node != null) + { + var next = node->Left; + _nodeStack.Push((nint)node); + node = next; + } + + return true; + } + + /// + /// Current + /// + public T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _current; + } + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _nodeStack.Dispose(); + } + + /// + /// Node color + /// + private enum NodeColor : byte + { + Black, + Red + } + + /// + /// Tree rotation + /// + private enum TreeRotation : byte + { + Left, + LeftRight, + Right, + RightLeft + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedSet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedSet.cs.meta new file mode 100644 index 00000000..6ced4841 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeSortedSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0caa62cbe6fc40269cb9da947e76599 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeStack.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeStack.cs new file mode 100644 index 00000000..5a295a26 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeStack.cs @@ -0,0 +1,425 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +#endif + +#pragma warning disable CA2208 +#pragma warning disable CS8632 + +// ReSharper disable ALL + +namespace NativeCollections +{ + /// + /// Native stack + /// + /// Type + [StructLayout(LayoutKind.Sequential)] + public readonly unsafe struct NativeStack : IDisposable, IEquatable> where T : unmanaged + { + /// + /// Handle + /// + [StructLayout(LayoutKind.Sequential)] + private struct NativeStackHandle + { + /// + /// Array + /// + public T* Array; + + /// + /// Length + /// + public int Length; + + /// + /// Size + /// + public int Size; + + /// + /// Version + /// + public int Version; + } + + /// + /// Handle + /// + private readonly NativeStackHandle* _handle; + + /// + /// Structure + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NativeStack(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (capacity < 4) + capacity = 4; + _handle = (NativeStackHandle*)NativeMemoryAllocator.Alloc((uint)sizeof(NativeStackHandle)); + _handle->Array = (T*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(T))); + _handle->Length = capacity; + _handle->Size = 0; + _handle->Version = 0; + } + + /// + /// Is created + /// + public bool IsCreated => _handle != null; + + /// + /// Is empty + /// + public bool IsEmpty => _handle->Size == 0; + + /// + /// Get reference + /// + /// Index + public ref T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Get reference + /// + /// Index + public ref T this[uint index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _handle->Array[index]; + } + + /// + /// Count + /// + public int Count => _handle->Size; + + /// + /// Equals + /// + /// Other + /// Equals + public bool Equals(NativeStack other) => other == this; + + /// + /// Equals + /// + /// object + /// Equals + public override bool Equals(object? obj) => obj is NativeStack nativeStack && nativeStack == this; + + /// + /// Get hashCode + /// + /// HashCode + public override int GetHashCode() => (int)(nint)_handle; + + /// + /// To string + /// + /// String + public override string ToString() => $"NativeStack<{typeof(T).Name}>"; + + /// + /// Equals + /// + /// Left + /// Right + /// Equals + public static bool operator ==(NativeStack left, NativeStack right) => left._handle == right._handle; + + /// + /// Not equals + /// + /// Left + /// Right + /// Not equals + public static bool operator !=(NativeStack left, NativeStack right) => left._handle != right._handle; + + /// + /// Dispose + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + if (_handle == null) + return; + NativeMemoryAllocator.Free(_handle->Array); + NativeMemoryAllocator.Free(_handle); + } + + /// + /// Clear + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + _handle->Size = 0; + _handle->Version++; + } + + /// + /// Push + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Push(in T item) + { + var size = _handle->Size; + if ((uint)size < (uint)_handle->Length) + { + _handle->Array[size] = item; + _handle->Version++; + _handle->Size = size + 1; + } + else + { + Grow(_handle->Size + 1); + _handle->Array[_handle->Size] = item; + _handle->Version++; + _handle->Size++; + } + } + + /// + /// Try push + /// + /// Item + /// Pushed + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPush(in T item) + { + var size = _handle->Size; + if ((uint)size < (uint)_handle->Length) + { + _handle->Array[size] = item; + _handle->Version++; + _handle->Size = size + 1; + return true; + } + + return false; + } + + /// + /// Pop + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Pop() + { + var size = _handle->Size - 1; + if ((uint)size >= (uint)_handle->Length) + throw new InvalidOperationException("EmptyStack"); + _handle->Version++; + _handle->Size = size; + var item = _handle->Array[size]; + return item; + } + + /// + /// Try pop + /// + /// Item + /// Popped + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPop(out T result) + { + var size = _handle->Size - 1; + if ((uint)size >= (uint)_handle->Length) + { + result = default; + return false; + } + + _handle->Version++; + _handle->Size = size; + result = _handle->Array[size]; + return true; + } + + /// + /// Peek + /// + /// Item + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Peek() + { + var size = _handle->Size - 1; + return (uint)size >= (uint)_handle->Length ? throw new InvalidOperationException("EmptyStack") : _handle->Array[size]; + } + + /// + /// Try peek + /// + /// Item + /// Peeked + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPeek(out T result) + { + var size = _handle->Size - 1; + if ((uint)size >= (uint)_handle->Length) + { + result = default; + return false; + } + + result = _handle->Array[size]; + return true; + } + + /// + /// Ensure capacity + /// + /// Capacity + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int EnsureCapacity(int capacity) + { + if (capacity < 0) + throw new ArgumentOutOfRangeException(nameof(capacity), capacity, "MustBeNonNegative"); + if (_handle->Length < capacity) + Grow(capacity); + return _handle->Length; + } + + /// + /// Trim excess + /// + /// New capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TrimExcess() + { + var threshold = (int)(_handle->Length * 0.9); + if (_handle->Size < threshold) + SetCapacity(_handle->Size); + return _handle->Length; + } + + /// + /// Set capacity + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SetCapacity(int capacity) + { + var newArray = (T*)NativeMemoryAllocator.Alloc((uint)(capacity * sizeof(T))); + if (_handle->Size > 0) + Unsafe.CopyBlockUnaligned(newArray, _handle->Array, (uint)(_handle->Length * sizeof(T))); + NativeMemoryAllocator.Free(_handle->Array); + _handle->Array = newArray; + _handle->Length = capacity; + } + + /// + /// Grow + /// + /// Capacity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Grow(int capacity) + { + var newCapacity = 2 * _handle->Length; + if ((uint)newCapacity > 2147483591) + newCapacity = 2147483591; + var expected = _handle->Length + 4; + newCapacity = newCapacity > expected ? newCapacity : expected; + if (newCapacity < capacity) + newCapacity = capacity; + SetCapacity(newCapacity); + } + + /// + /// Empty + /// + public static NativeStack Empty => new(); + + /// + /// Get enumerator + /// + /// Enumerator + public Enumerator GetEnumerator() => new(this); + + /// + /// Enumerator + /// + public struct Enumerator + { + /// + /// NativeStack + /// + private readonly NativeStack _nativeStack; + + /// + /// Version + /// + private readonly int _version; + + /// + /// Index + /// + private int _index; + + /// + /// Current element + /// + private T _currentElement; + + /// + /// Structure + /// + /// NativeStack + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(in NativeStack nativeStack) + { + _nativeStack = nativeStack; + _version = nativeStack._handle->Version; + _index = -2; + _currentElement = default; + } + + /// + /// Move next + /// + /// Moved + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + if (_version != _nativeStack._handle->Version) + throw new InvalidOperationException("EnumFailedVersion"); + bool returned; + if (_index == -2) + { + _index = _nativeStack._handle->Size - 1; + returned = _index >= 0; + if (returned) + _currentElement = _nativeStack._handle->Array[_index]; + return returned; + } + + if (_index == -1) + return false; + returned = --_index >= 0; + _currentElement = returned ? _nativeStack._handle->Array[_index] : default; + return returned; + } + + /// + /// Current + /// + public T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _index < 0 ? throw new InvalidOperationException(_index == -1 ? "EnumNotStarted" : "EnumEnded") : _currentElement; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeStack.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeStack.cs.meta new file mode 100644 index 00000000..084a941d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/NativeCollections/NativeStack.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e743287c1428842cb84bffacf9ffcc39 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/README.md b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/README.md new file mode 100644 index 00000000..c3b41cf7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/README.md @@ -0,0 +1,3 @@ +# NativeCollections + +This project is a pure C# native collections for (Unity/Godot/.NET) \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/README.md.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/README.md.meta new file mode 100644 index 00000000..becb4069 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/NativeCollections/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b01660bc17b1a4f60bdf2a71837899c6 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue.meta new file mode 100644 index 00000000..b926d223 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2af7e2648850348b591adabb5ba44532 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs new file mode 100644 index 00000000..2ef67040 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs @@ -0,0 +1,121 @@ +// ReSharper disable SwapViaDeconstruction +// ReSharper disable UseIndexFromEndExpression +// ReSharper disable ConvertToPrimaryConstructor +using System; +using System.Collections.Generic; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.DataStructure.PriorityQueue +{ + /// + /// 优先队列 + /// + /// 节点数据 + /// 排序的类型、 + public sealed class PriorityQueue where TPriority : IComparable + { + private readonly List> _heap; + + public PriorityQueue(int initialCapacity = 16) + { + _heap = new List>(initialCapacity); + } + + public int Count => _heap.Count; + + public void Enqueue(TElement element, TPriority priority) + { + _heap.Add(new PriorityQueueItem(element, priority)); + HeapifyUp(_heap.Count - 1); + } + + public TElement Dequeue() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + + var item = _heap[0]; + _heap[0] = _heap[_heap.Count - 1]; + _heap.RemoveAt(_heap.Count - 1); + HeapifyDown(0); + return item.Element; + } + + public bool TryDequeue(out TElement element) + { + if (_heap.Count == 0) + { + element = default(TElement); + return false; + } + + element = Dequeue(); + return true; + } + + public TElement Peek() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + return _heap[0].Element; + } + + // ReSharper disable once IdentifierTypo + private void HeapifyUp(int index) + { + while (index > 0) + { + var parentIndex = (index - 1) / 2; + if (_heap[index].Priority.CompareTo(_heap[parentIndex].Priority) >= 0) + { + break; + } + Swap(index, parentIndex); + index = parentIndex; + } + } + + // ReSharper disable once IdentifierTypo + private void HeapifyDown(int index) + { + var lastIndex = _heap.Count - 1; + while (true) + { + var smallestIndex = index; + var leftChildIndex = 2 * index + 1; + var rightChildIndex = 2 * index + 2; + + if (leftChildIndex <= lastIndex && _heap[leftChildIndex].Priority.CompareTo(_heap[smallestIndex].Priority) < 0) + { + smallestIndex = leftChildIndex; + } + + if (rightChildIndex <= lastIndex && _heap[rightChildIndex].Priority.CompareTo(_heap[smallestIndex].Priority) < 0) + { + smallestIndex = rightChildIndex; + } + + if (smallestIndex == index) + { + break; + } + + Swap(index, smallestIndex); + index = smallestIndex; + } + } + + private void Swap(int index1, int index2) + { + var temp = _heap[index1]; + _heap[index1] = _heap[index2]; + _heap[index2] = temp; + } + } +} + diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta new file mode 100644 index 00000000..cd9ba0b2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueGenerics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0fb73a1acb1843ad86127be8503ed92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs new file mode 100644 index 00000000..5b020b2a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs @@ -0,0 +1,30 @@ +// ReSharper disable ConvertToPrimaryConstructor +// ReSharper disable SwapViaDeconstruction +// ReSharper disable InconsistentNaming +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.DataStructure.PriorityQueue +{ + public struct PriorityQueueItemUint + { + public T Element { get; set; } + public uint Priority { get; set; } + + public PriorityQueueItemUint(T element, uint priority) + { + Element = element; + Priority = priority; + } + } + + public struct PriorityQueueItem + { + public T Element { get; } + public T1 Priority { get; } + + public PriorityQueueItem(T element, T1 priority) + { + Element = element; + Priority = priority; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta new file mode 100644 index 00000000..17b47a5a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79c4ab0531d874383b52d8b7082cf3a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs new file mode 100644 index 00000000..63a4418b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs @@ -0,0 +1,116 @@ +// ReSharper disable SwapViaDeconstruction +// ReSharper disable UseIndexFromEndExpression +// ReSharper disable ConvertToPrimaryConstructor +using System; +using System.Collections.Generic; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.DataStructure.PriorityQueue +{ + public sealed class PriorityQueue where T : IComparable + { + private readonly List _heap; + + public PriorityQueue(int initialCapacity = 16) + { + _heap = new List(initialCapacity); + } + + public int Count => _heap.Count; + + public void Enqueue(T item) + { + _heap.Add(item); + HeapifyUp(_heap.Count - 1); + } + + public T Dequeue() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + + var item = _heap[0]; + var heapCount = _heap.Count - 1; + _heap[0] = _heap[heapCount]; + _heap.RemoveAt(heapCount); + HeapifyDown(0); + return item; + } + + public bool TryDequeue(out T item) + { + if (_heap.Count == 0) + { + item = default(T); + return false; + } + + item = Dequeue(); + return true; + } + + public T Peek() + { + if (_heap.Count == 0) + { + throw new InvalidOperationException("The queue is empty."); + } + return _heap[0]; + } + + // ReSharper disable once IdentifierTypo + private void HeapifyUp(int index) + { + while (index > 0) + { + var parentIndex = (index - 1) / 2; + if (_heap[index].CompareTo(_heap[parentIndex]) >= 0) + { + break; + } + Swap(index, parentIndex); + index = parentIndex; + } + } + + // ReSharper disable once IdentifierTypo + private void HeapifyDown(int index) + { + var lastIndex = _heap.Count - 1; + while (true) + { + var smallestIndex = index; + var leftChildIndex = 2 * index + 1; + var rightChildIndex = 2 * index + 2; + + if (leftChildIndex <= lastIndex && _heap[leftChildIndex].CompareTo(_heap[smallestIndex]) < 0) + { + smallestIndex = leftChildIndex; + } + + if (rightChildIndex <= lastIndex && _heap[rightChildIndex].CompareTo(_heap[smallestIndex]) < 0) + { + smallestIndex = rightChildIndex; + } + + if (smallestIndex == index) + { + break; + } + + Swap(index, smallestIndex); + index = smallestIndex; + } + } + + private void Swap(int index1, int index2) + { + var temp = _heap[index1]; + _heap[index1] = _heap[index2]; + _heap[index2] = temp; + } + } +} + diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta new file mode 100644 index 00000000..0cc767ab --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/PriorityQueue/PriorityQueueSimple.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c604a0410d104d68a5d1718a570e5c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable.meta new file mode 100644 index 00000000..2361a4cc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 68c20f8b3fb7f461f9b2f22aa39b4c2e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTable.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTable.cs new file mode 100644 index 00000000..acbc2c1f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTable.cs @@ -0,0 +1,190 @@ + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 跳表数据结构(升序版) + /// + /// 跳表中存储的值的类型。 + public class SkipTable : SkipTableBase + { + /// + /// 创建一个新的跳表实例。 + /// + /// 跳表的最大层数。 + public SkipTable(int maxLayer = 8) : base(maxLayer) { } + + /// + /// 向跳表中添加一个新节点。 + /// + /// 节点的主排序键。 + /// 节点的副排序键。 + /// 节点的唯一键。 + /// 要添加的值。 + public override void Add(long sortKey, long viceKey, long key, TValue value) + { + var rLevel = 1; + + while (rLevel <= MaxLayer && Random.Next(3) == 0) + { + ++rLevel; + } + + SkipTableNode cur = TopHeader, last = null; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 节点有next节点,且 (next主键 < 插入主键) 或 (next主键 == 插入主键 且 next副键 < 插入副键) + while (cur.Right != null && ((cur.Right.SortKey < sortKey) || + (cur.Right.SortKey == sortKey && cur.Right.ViceKey < viceKey))) + { + cur = cur.Right; + } + + if (layer <= rLevel) + { + var currentRight = cur.Right; + + // 在当前层插入新节点 + cur.Right = new SkipTableNode(sortKey, viceKey, key, value, layer == 1 ? cur.Index + 1 : 0, cur, cur.Right, null); + + if (currentRight != null) + { + currentRight.Left = cur.Right; + } + + if (last != null) + { + last.Down = cur.Right; + } + + if (layer == 1) + { + // 更新索引信息 + cur.Right.Index = cur.Index + 1; + Node.Add(key, cur.Right); + + SkipTableNode v = cur.Right.Right; + + while (v != null) + { + v.Index++; + v = v.Right; + } + } + + last = cur.Right; + } + + cur = cur.Down; + } + } + + /// + /// 从跳表中移除一个节点。 + /// + /// 节点的主排序键。 + /// 节点的副排序键。 + /// 节点的唯一键。 + /// 被移除的节点的值。 + /// 如果成功移除节点,则为 true;否则为 false。 + public override bool Remove(long sortKey, long viceKey, long key, out TValue value) + { + value = default; + var seen = false; + var cur = TopHeader; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 先按照主键查找 再 按副键查找 + while (cur.Right != null && cur.Right.SortKey < sortKey && cur.Right.Key != key) cur = cur.Right; + while (cur.Right != null && (cur.Right.SortKey == sortKey && cur.Right.ViceKey <= viceKey) && + cur.Right.Key != key) cur = cur.Right; + + var isFind = false; + var currentCur = cur; + SkipTableNode removeCur = null; + // 如果当前不是要删除的节点、但主键和副键都一样、需要特殊处理下。 + if (cur.Right != null && cur.Right.Key == key) + { + isFind = true; + removeCur = cur.Right; + currentCur = cur; + } + else + { + // 先向左查找下 + var currentNode = cur.Left; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Left; + } + + // 再向右查找下 + if (!isFind) + { + currentNode = cur.Right; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Right; + } + } + } + + if (isFind && currentCur != null) + { + value = removeCur.Value; + currentCur.Right = removeCur.Right; + + if (removeCur.Right != null) + { + removeCur.Right.Left = currentCur; + removeCur.Right = null; + } + + removeCur.Left = null; + removeCur.Down = null; + removeCur.Value = default; + + if (layer == 1) + { + var tempCur = currentCur.Right; + while (tempCur != null) + { + tempCur.Index--; + tempCur = tempCur.Right; + } + + Node.Remove(removeCur.Key); + } + + seen = true; + } + + cur = cur.Down; + } + + return seen; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTable.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTable.cs.meta new file mode 100644 index 00000000..ebd23fe1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45fbcdc219ef843aaa31594eb4e76a5b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableBase.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableBase.cs new file mode 100644 index 00000000..82783e81 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableBase.cs @@ -0,0 +1,282 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Fantasy.DataStructure.Collection; + +#pragma warning disable CS8601 +#pragma warning disable CS8603 +#pragma warning disable CS8625 +#pragma warning disable CS8604 + +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 抽象的跳表基类,提供跳表的基本功能和操作。 + /// + /// 跳表中存储的值的类型。 + public abstract class SkipTableBase : IEnumerable> + { + /// + /// 跳表的最大层数 + /// + public readonly int MaxLayer; + /// + /// 跳表的顶部头节点 + /// + public readonly SkipTableNode TopHeader; + /// + /// 跳表的底部头节点 + /// + public SkipTableNode BottomHeader; + /// + /// 跳表中节点的数量,使用了 Node 字典的计数 + /// + public int Count => Node.Count; + /// + /// 用于生成随机数的随机数生成器 + /// + protected readonly Random Random = new Random(); + /// + /// 存储跳表节点的字典 + /// + protected readonly Dictionary> Node = new(); + /// + /// 用于辅助反向查找的栈 + /// + protected readonly Stack> AntiFindStack = new Stack>(); + + /// + /// 初始化一个新的跳表实例。 + /// + /// 跳表的最大层数,默认为 8。 + protected SkipTableBase(int maxLayer = 8) + { + MaxLayer = maxLayer; + var cur = TopHeader = new SkipTableNode(long.MinValue, 0, 0, default, 0, null, null, null); + + for (var layer = MaxLayer - 1; layer >= 1; --layer) + { + cur.Down = new SkipTableNode(long.MinValue, 0, 0, default, 0, null, null, null); + cur = cur.Down; + } + + BottomHeader = cur; + } + + /// + /// 获取指定键的节点的值,若不存在则返回默认值。 + /// + /// 要查找的键。 + public TValue this[long key] => !TryGetValueByKey(key, out TValue value) ? default : value; + + /// + /// 获取指定键的节点在跳表中的排名。 + /// + /// 要查找的键。 + /// 节点的排名。 + public int GetRanking(long key) + { + if (!Node.TryGetValue(key, out var node)) + { + return 0; + } + + return node.Index; + } + + /// + /// 获取指定键的反向排名,即在比该键更大的节点中的排名。 + /// + /// 要查找的键。 + /// 反向排名。 + public int GetAntiRanking(long key) + { + var ranking = GetRanking(key); + + if (ranking == 0) + { + return 0; + } + + return Count + 1 - ranking; + } + + /// + /// 尝试通过键获取节点的值。 + /// + /// 要查找的键。 + /// 获取到的节点的值,如果键不存在则为默认值。 + /// 是否成功获取节点的值。 + public bool TryGetValueByKey(long key, out TValue value) + { + if (!Node.TryGetValue(key, out var node)) + { + value = default; + return false; + } + + value = node.Value; + return true; + } + + /// + /// 尝试通过键获取节点。 + /// + /// 要查找的键。 + /// 获取到的节点,如果键不存在则为 null。 + /// 是否成功获取节点。 + public bool TryGetNodeByKey(long key, out SkipTableNode node) + { + if (Node.TryGetValue(key, out node)) + { + return true; + } + + return false; + } + + /// + /// 在跳表中查找节点,返回从起始位置到结束位置的节点列表。 + /// + /// 起始位置的排名。 + /// 结束位置的排名。 + /// 用于存储节点列表的 实例。 + public void Find(int start, int end, ListPool> list) + { + var cur = BottomHeader; + var count = end - start; + + for (var i = 0; i < start; i++) + { + cur = cur.Right; + } + + for (var i = 0; i <= count; i++) + { + if (cur == null) + { + break; + } + + list.Add(cur); + cur = cur.Right; + } + } + + /// + /// 在跳表中进行反向查找节点,返回从结束位置到起始位置的节点列表。 + /// + /// 结束位置的排名。 + /// 起始位置的排名。 + /// 用于存储节点列表的 实例。 + public void AntiFind(int start, int end, ListPool> list) + { + var cur = BottomHeader; + start = Count + 1 - start; + end = start - end; + + for (var i = 0; i < start; i++) + { + cur = cur.Right; + + if (cur == null) + { + break; + } + + if (i < end) + { + continue; + } + + AntiFindStack.Push(cur); + } + + while (AntiFindStack.TryPop(out var node)) + { + list.Add(node); + } + } + + /// + /// 获取跳表中最后一个节点的值。 + /// + /// 最后一个节点的值。 + public TValue GetLastValue() + { + var cur = TopHeader; + + while (cur.Right != null || cur.Down != null) + { + while (cur.Right != null) + { + cur = cur.Right; + } + + if (cur.Down != null) + { + cur = cur.Down; + } + } + + return cur.Value; + } + + /// + /// 移除跳表中指定键的节点。 + /// + /// 要移除的节点的键。 + /// 移除是否成功。 + public bool Remove(long key) + { + if (!Node.TryGetValue(key, out var node)) + { + return false; + } + + return Remove(node.SortKey, node.ViceKey, key, out _); + } + + /// + /// 向跳表中添加节点。 + /// + /// 节点的排序键。 + /// 节点的副键。 + /// 节点的键。 + /// 节点的值。 + public abstract void Add(long sortKey, long viceKey, long key, TValue value); + + /// + /// 从跳表中移除指定键的节点。 + /// + /// 节点的排序键。 + /// 节点的副键。 + /// 节点的键。 + /// 被移除的节点的值。 + /// 移除是否成功。 + public abstract bool Remove(long sortKey, long viceKey, long key, out TValue value); + + /// + /// 返回一个枚举器,用于遍历跳表中的节点。 + /// + /// 一个可用于遍历跳表节点的枚举器。 + public IEnumerator> GetEnumerator() + { + var cur = BottomHeader.Right; + while (cur != null) + { + yield return cur; + cur = cur.Right; + } + } + + /// + /// 返回一个非泛型枚举器,用于遍历跳表中的节点。 + /// + /// 一个非泛型枚举器,可用于遍历跳表节点。 + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta new file mode 100644 index 00000000..500fa2d1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c70c703e84d842b9b488dd0798290d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableDesc.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableDesc.cs new file mode 100644 index 00000000..63daa16c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableDesc.cs @@ -0,0 +1,188 @@ + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 跳表降序版,用于存储降序排列的数据。 + /// + /// 存储的值的类型。 + public class SkipTableDesc : SkipTableBase + { + /// + /// 初始化跳表降序版的新实例。 + /// + /// 跳表的最大层数,默认为 8。 + public SkipTableDesc(int maxLayer = 8) : base(maxLayer) { } + + /// + /// 向跳表中添加一个节点,根据降序规则进行插入。 + /// + /// 排序主键。 + /// 副键。 + /// 键。 + /// 值。 + public override void Add(long sortKey, long viceKey, long key, TValue value) + { + var rLevel = 1; + + while (rLevel <= MaxLayer && Random.Next(3) == 0) + { + ++rLevel; + } + + SkipTableNode cur = TopHeader, last = null; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 节点有next节点,且 (next主键 > 插入主键) 或 (next主键 == 插入主键 且 next副键 > 插入副键) + while (cur.Right != null && ((cur.Right.SortKey > sortKey) || + (cur.Right.SortKey == sortKey && cur.Right.ViceKey > viceKey))) + { + cur = cur.Right; + } + + if (layer <= rLevel) + { + var currentRight = cur.Right; + cur.Right = new SkipTableNode(sortKey, viceKey, key, value, + layer == 1 ? cur.Index + 1 : 0, cur, cur.Right, null); + + if (currentRight != null) + { + currentRight.Left = cur.Right; + } + + if (last != null) + { + last.Down = cur.Right; + } + + if (layer == 1) + { + cur.Right.Index = cur.Index + 1; + Node.Add(key, cur.Right); + + SkipTableNode v = cur.Right.Right; + + while (v != null) + { + v.Index++; + v = v.Right; + } + } + + last = cur.Right; + } + + cur = cur.Down; + } + } + + /// + /// 从跳表中移除一个节点,根据降序规则进行移除。 + /// + /// 排序主键。 + /// 副键。 + /// 键。 + /// 移除的节点值。 + /// 如果成功移除节点,则返回 true,否则返回 false。 + public override bool Remove(long sortKey, long viceKey, long key, out TValue value) + { + value = default; + var seen = false; + var cur = TopHeader; + + for (var layer = MaxLayer; layer >= 1; --layer) + { + // 先按照主键查找 再 按副键查找 + while (cur.Right != null && cur.Right.SortKey > sortKey && cur.Right.Key != key) cur = cur.Right; + while (cur.Right != null && (cur.Right.SortKey == sortKey && cur.Right.ViceKey >= viceKey) && + cur.Right.Key != key) cur = cur.Right; + + var isFind = false; + var currentCur = cur; + SkipTableNode removeCur = null; + // 如果当前不是要删除的节点、但主键和副键都一样、需要特殊处理下。 + if (cur.Right != null && cur.Right.Key == key) + { + isFind = true; + removeCur = cur.Right; + currentCur = cur; + } + else + { + // 先向左查找下 + var currentNode = cur.Left; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Left; + } + + // 再向右查找下 + if (!isFind) + { + currentNode = cur.Right; + while (currentNode != null && currentNode.SortKey == sortKey && currentNode.ViceKey == viceKey) + { + if (currentNode.Key == key) + { + isFind = true; + removeCur = currentNode; + currentCur = currentNode.Left; + break; + } + + currentNode = currentNode.Right; + } + } + } + + if (isFind && currentCur != null) + { + value = removeCur.Value; + currentCur.Right = removeCur.Right; + + if (removeCur.Right != null) + { + removeCur.Right.Left = currentCur; + removeCur.Right = null; + } + + removeCur.Left = null; + removeCur.Down = null; + removeCur.Value = default; + + if (layer == 1) + { + var tempCur = currentCur.Right; + while (tempCur != null) + { + tempCur.Index--; + tempCur = tempCur.Right; + } + + Node.Remove(removeCur.Key); + } + + seen = true; + } + + cur = cur.Down; + } + + return seen; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta new file mode 100644 index 00000000..7a588807 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableDesc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae15364981a674c59a2e20d2b99f097b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableNode.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableNode.cs new file mode 100644 index 00000000..8a1a1446 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableNode.cs @@ -0,0 +1,68 @@ +namespace Fantasy.DataStructure.SkipTable +{ + /// + /// 跳跃表节点。 + /// + /// 节点的值的类型。 + public class SkipTableNode + { + /// + /// 节点在跳跃表中的索引。 + /// + public int Index; + /// + /// 节点的主键。 + /// + public long Key; + /// + /// 节点的排序键。 + /// + public long SortKey; + /// + /// 节点的副键。 + /// + public long ViceKey; + /// + /// 节点存储的值。 + /// + public TValue Value; + /// + /// 指向左侧节点的引用。 + /// + public SkipTableNode Left; + /// + /// 指向右侧节点的引用。 + /// + public SkipTableNode Right; + /// + /// 指向下一层节点的引用。 + /// + public SkipTableNode Down; + + /// + /// 初始化跳跃表节点的新实例。 + /// + /// 节点的排序键。 + /// 节点的副键。 + /// 节点的主键。 + /// 节点存储的值。 + /// 节点在跳跃表中的索引。 + /// 指向左侧节点的引用。 + /// 指向右侧节点的引用。 + /// 指向下一层节点的引用。 + public SkipTableNode(long sortKey, long viceKey, long key, TValue value, int index, + SkipTableNode l, + SkipTableNode r, + SkipTableNode d) + { + Left = l; + Right = r; + Down = d; + Value = value; + Key = key; + Index = index; + SortKey = sortKey; + ViceKey = viceKey; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta new file mode 100644 index 00000000..c3154ea3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/DataStructure/SkipTable/SkipTableNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9384bd7a2a46f401ea6de3461b5aa36b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas.meta new file mode 100644 index 00000000..9f741206 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 27462e8175ff84272b8b14c7b2ffb00c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component.meta new file mode 100644 index 00000000..01ffb2b2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e39207f0f9770415093af2f27fd7e988 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock.meta new file mode 100644 index 00000000..779e6f28 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: db6a6392f9f6e4a2fbedb6ba3df377e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs new file mode 100644 index 00000000..7536b0b7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using Cysharp.Threading.Tasks; +using Fantasy.Pool; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.Async +{ + /// + /// 协程锁专用的对象池 + /// + public sealed class CoroutineLockPool : PoolCore + { + /// + /// 协程锁专用的对象池的构造函数 + /// + public CoroutineLockPool() : base(2000) { } + } + + /// + /// 协程锁 + /// + public sealed class CoroutineLock : IPool, IDisposable + { + private Scene _scene; + private CoroutineLockComponent _coroutineLockComponent; + private readonly Dictionary _queue = new Dictionary(); + /// + /// 表示是否是对象池中创建的 + /// + private bool _isPool; + /// + /// 协程锁的类型 + /// + public long CoroutineLockType { get; private set; } + + internal void Initialize(CoroutineLockComponent coroutineLockComponent, ref long coroutineLockType) + { + _scene = coroutineLockComponent.Scene; + CoroutineLockType = coroutineLockType; + _coroutineLockComponent = coroutineLockComponent; + } + /// + /// 销毁协程锁,如果调用了该方法,所有使用当前协程锁等待的逻辑会按照顺序释放锁。 + /// + public void Dispose() + { + foreach (var (_, coroutineLockQueue) in _queue) + { + while (TryCoroutineLockQueueDequeue(coroutineLockQueue)) { } + } + + _queue.Clear(); + _scene = null; + CoroutineLockType = 0; + _coroutineLockComponent = null; + } + /// + /// 等待上一个任务完成 + /// + /// 需要等待的Id + /// 用于查询协程锁的标记,可不传入,只有在超时的时候排查是哪个锁超时时使用 + /// 等待多久会超时,当到达设定的时候会把当前锁给按照超时处理 + /// + public async UniTask Wait(long coroutineLockQueueKey, string tag = null, int timeOut = 30000) + { + var waitCoroutineLock = _coroutineLockComponent.WaitCoroutineLockPool.Rent(this, ref coroutineLockQueueKey, tag, timeOut); + + if (!_queue.TryGetValue(coroutineLockQueueKey, out var queue)) + { + queue = _coroutineLockComponent.CoroutineLockQueuePool.Rent(); + _queue.Add(coroutineLockQueueKey, queue); + return waitCoroutineLock; + } + + queue.Enqueue(waitCoroutineLock); + return await waitCoroutineLock.Tcs.Task; + } + /// + /// 按照先入先出的顺序,释放最早的一个协程锁 + /// + /// + public void Release(long coroutineLockQueueKey) + { + if (!_queue.TryGetValue(coroutineLockQueueKey, out var coroutineLockQueue)) + { + return; + } + + if (!TryCoroutineLockQueueDequeue(coroutineLockQueue)) + { + _queue.Remove(coroutineLockQueueKey); + } + } + + private bool TryCoroutineLockQueueDequeue(CoroutineLockQueue coroutineLockQueue) + { + if (!coroutineLockQueue.TryDequeue(out var waitCoroutineLock)) + { + _coroutineLockComponent.CoroutineLockQueuePool.Return(coroutineLockQueue); + return false; + } + + if (waitCoroutineLock.TimerId != 0) + { + _scene.TimerComponent.Net.Remove(waitCoroutineLock.TimerId); + } + + try + { + // 放到下一帧执行,如果不这样会导致逻辑的顺序不正常。 + _scene.ThreadSynchronizationContext.Post(waitCoroutineLock.SetResult); + } + catch (Exception e) + { + Log.Error($"Error in disposing CoroutineLock: {e}"); + } + + return true; + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta new file mode 100644 index 00000000..d67163de --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2fe8fb8f49ad4565b47c840fb690d1f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs new file mode 100644 index 00000000..fa831baf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using Cysharp.Threading.Tasks; +using Fantasy.Entitas; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Async +{ + /// + /// 协程锁组件 + /// + public class CoroutineLockComponent : Entity + { + private long _lockId; + private CoroutineLockPool _coroutineLockPool; + internal WaitCoroutineLockPool WaitCoroutineLockPool { get; private set; } + internal CoroutineLockQueuePool CoroutineLockQueuePool { get; private set; } + private readonly Dictionary _coroutineLocks = new Dictionary(); + internal CoroutineLockComponent Initialize() + { + _coroutineLockPool = new CoroutineLockPool(); + CoroutineLockQueuePool = new CoroutineLockQueuePool(); + WaitCoroutineLockPool = new WaitCoroutineLockPool(this); + return this; + } + + internal long LockId => ++_lockId; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public override void Dispose() +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + { + if (IsDisposed) + { + return; + } + + _lockId = 0; + base.Dispose(); + } + + /// + /// 创建一个新的协程锁 + /// 使用这个方法创建的协程锁,需要手动释放管理CoroutineLock。 + /// 不会再CoroutineLockComponent理进行管理。 + /// + /// + /// + public CoroutineLock Create(long coroutineLockType) + { + var coroutineLock = _coroutineLockPool.Rent(); + coroutineLock.Initialize(this, ref coroutineLockType); + return coroutineLock; + } + + /// + /// 请求一个协程锁。 + /// 使用这个方法创建的协程锁,会自动释放CoroutineLockQueueType。 + /// + /// 锁类型 + /// 锁队列Id + /// 当某些锁超时,需要一个标记来方便排查问题,正常的情况下这个默认为null就可以。 + /// 设置锁的超时时间,让超过设置的时间会触发超时,保证锁不会因为某一个锁一直不解锁导致卡住的问题。 + /// + /// 返回的WaitCoroutineLock通过Dispose来解除这个锁、建议用using来保住这个锁。 + /// 也可以返回的WaitCoroutineLock通过CoroutineLockComponent.UnLock来解除这个锁。 + /// + public UniTask Wait(long coroutineLockType, long coroutineLockQueueKey, string tag = null, int time = 30000) + { + if (!_coroutineLocks.TryGetValue(coroutineLockType, out var coroutineLock)) + { + coroutineLock = _coroutineLockPool.Rent(); + coroutineLock.Initialize(this, ref coroutineLockType); + _coroutineLocks.Add(coroutineLockType, coroutineLock); + } + + return coroutineLock.Wait(coroutineLockQueueKey, tag, time); + } + + /// + /// 解除一个协程锁。 + /// + /// + /// + public void Release(int coroutineLockType, long coroutineLockQueueKey) + { + if (IsDisposed) + { + return; + } + + if (!_coroutineLocks.TryGetValue(coroutineLockType, out var coroutineLock)) + { + return; + } + + coroutineLock.Release(coroutineLockQueueKey); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta new file mode 100644 index 00000000..c4a03b1e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8abfde11ad4d344eda0bf16b249a0dae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs new file mode 100644 index 00000000..2948aca2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs @@ -0,0 +1,35 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.Async +{ + internal sealed class CoroutineLockQueuePool : PoolCore + { + public CoroutineLockQueuePool() : base(2000) { } + } + + internal sealed class CoroutineLockQueue : Queue, IPool + { + private bool _isPool; + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta new file mode 100644 index 00000000..1e55b8c4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/CoroutineLockQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c1a15c49a7b7b488c8aac3d7720d506e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs new file mode 100644 index 00000000..6dbbb6a1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs @@ -0,0 +1,147 @@ +using System; +using Cysharp.Threading.Tasks; +using Fantasy.Event; +using Fantasy.Pool; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Async +{ + internal sealed class WaitCoroutineLockPool : PoolCore + { + private readonly Scene _scene; + private readonly CoroutineLockComponent _coroutineLockComponent; + + public WaitCoroutineLockPool(CoroutineLockComponent coroutineLockComponent) : base(2000) + { + _scene = coroutineLockComponent.Scene; + _coroutineLockComponent = coroutineLockComponent; + } + + public WaitCoroutineLock Rent(CoroutineLock coroutineLock, ref long coroutineLockQueueKey, string tag = null, int timeOut = 30000) + { + var timerId = 0L; + var lockId = _coroutineLockComponent.LockId; + var waitCoroutineLock = _coroutineLockComponent.WaitCoroutineLockPool.Rent(); + + if (timeOut > 0) + { + timerId = _scene.TimerComponent.Net.OnceTimer(timeOut, new CoroutineLockTimeout(ref lockId, waitCoroutineLock)); + } + + waitCoroutineLock.Initialize(coroutineLock, this, ref coroutineLockQueueKey, ref timerId, ref lockId, tag); + return waitCoroutineLock; + } + } + + internal struct CoroutineLockTimeout + { + public readonly long LockId; + public readonly WaitCoroutineLock WaitCoroutineLock; + + public CoroutineLockTimeout(ref long lockId, WaitCoroutineLock waitCoroutineLock) + { + LockId = lockId; + WaitCoroutineLock = waitCoroutineLock; + } + } + + internal sealed class OnCoroutineLockTimeout : EventSystem + { + protected override void Handler(CoroutineLockTimeout self) + { + var selfWaitCoroutineLock = self.WaitCoroutineLock; + + if (self.LockId != selfWaitCoroutineLock.LockId) + { + return; + } + + Log.Error($"coroutine lock timeout CoroutineLockQueueType:{selfWaitCoroutineLock.CoroutineLock.CoroutineLockType} Key:{selfWaitCoroutineLock.CoroutineLockQueueKey} Tag:{selfWaitCoroutineLock.Tag}"); + } + } + + /// + /// 一个协程锁的实例,用户可以用过这个手动释放锁 + /// + public sealed class WaitCoroutineLock : IPool, IDisposable + { + private bool _isPool; + internal string Tag { get; private set; } + internal long LockId { get; private set; } + internal long TimerId { get; private set; } + internal long CoroutineLockQueueKey { get; private set; } + internal CoroutineLock CoroutineLock { get; private set; } + + private bool _isSetResult; + private AutoResetUniTaskCompletionSourcePlus _tcs; + private WaitCoroutineLockPool _waitCoroutineLockPool; + internal void Initialize(CoroutineLock coroutineLock, WaitCoroutineLockPool waitCoroutineLockPool, ref long coroutineLockQueueKey, ref long timerId, ref long lockId, string tag) + { + Tag = tag; + LockId = lockId; + TimerId = timerId; + CoroutineLock = coroutineLock; + CoroutineLockQueueKey = coroutineLockQueueKey; + _waitCoroutineLockPool = waitCoroutineLockPool; + } + /// + /// 释放协程锁 + /// + public void Dispose() + { + if (LockId == 0) + { + Log.Error("WaitCoroutineLock is already disposed"); + return; + } + + CoroutineLock.Release(CoroutineLockQueueKey); + + _tcs = null; + Tag = null; + LockId = 0; + TimerId = 0; + _isSetResult = false; + CoroutineLockQueueKey = 0; + _waitCoroutineLockPool.Return(this); + CoroutineLock = null; + _waitCoroutineLockPool = null; + } + + internal AutoResetUniTaskCompletionSourcePlus Tcs + { + get { return _tcs ??= AutoResetUniTaskCompletionSourcePlus.Create(); } + } + + internal void SetResult() + { + if (_isSetResult) + { + Log.Error("WaitCoroutineLock is already SetResult"); + return; + } + + _isSetResult = true; + Tcs.TrySetResult(this); + } + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta new file mode 100644 index 00000000..9aa7508e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/CoroutineLock/WaitCoroutineLock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6d5307f677ba48f891c12ac183a0128 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EntityComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EntityComponent.cs new file mode 100644 index 00000000..03abe875 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EntityComponent.cs @@ -0,0 +1,399 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Cysharp.Threading.Tasks; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; + +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Entitas +{ + internal sealed class UpdateQueueInfo + { + public bool IsStop; + public readonly Type Type; + public readonly long RunTimeId; + + public UpdateQueueInfo(Type type, long runTimeId) + { + Type = type; + IsStop = false; + RunTimeId = runTimeId; + } + } + + internal sealed class FrameUpdateQueueInfo + { + public readonly Type Type; + public readonly long RunTimeId; + + public FrameUpdateQueueInfo(Type type, long runTimeId) + { + Type = type; + RunTimeId = runTimeId; + } + } + + /// + /// Entity管理组件 + /// + public sealed class EntityComponent : Entity, ISceneUpdate, IAssembly + { + private readonly OneToManyList _assemblyList = new(); + private readonly OneToManyList _assemblyHashCodes = new(); + + private readonly Dictionary _awakeSystems = new(); + private readonly Dictionary _updateSystems = new(); + private readonly Dictionary _destroySystems = new(); + private readonly Dictionary _deserializeSystems = new(); + private readonly Dictionary _frameUpdateSystem = new(); + + private readonly Dictionary _hashCodes = new Dictionary(); + private readonly Queue _updateQueue = new Queue(); + private readonly Queue _frameUpdateQueue = new Queue(); + private readonly Dictionary _updateQueueDic = new Dictionary(); + + internal async UniTask Initialize() + { + await AssemblySystem.Register(this); + return this; + } + + #region Assembly + + public UniTask Load(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + return tcs.Task; + } + + public UniTask ReLoad(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + return tcs.Task; + } + + public UniTask OnUnLoad(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + return tcs.Task; + } + + private void LoadInner(long assemblyIdentity) + { + foreach (var entityType in AssemblySystem.ForEach(assemblyIdentity, typeof(IEntity))) + { + _hashCodes.Add(entityType, HashCodeHelper.ComputeHash64(entityType.FullName)); + _assemblyHashCodes.Add(assemblyIdentity, entityType); + } + + foreach (var entitiesSystemType in AssemblySystem.ForEach(assemblyIdentity, typeof(IEntitiesSystem))) + { + Type entitiesType = null; + var entity = Activator.CreateInstance(entitiesSystemType); + + switch (entity) + { + case IAwakeSystem iAwakeSystem: + { + entitiesType = iAwakeSystem.EntitiesType(); + _awakeSystems.Add(entitiesType, iAwakeSystem); + break; + } + case IDestroySystem iDestroySystem: + { + entitiesType = iDestroySystem.EntitiesType(); + _destroySystems.Add(entitiesType, iDestroySystem); + break; + } + case IDeserializeSystem iDeserializeSystem: + { + entitiesType = iDeserializeSystem.EntitiesType(); + _deserializeSystems.Add(entitiesType, iDeserializeSystem); + break; + } + case IUpdateSystem iUpdateSystem: + { + entitiesType = iUpdateSystem.EntitiesType(); + _updateSystems.Add(entitiesType, iUpdateSystem); + break; + } + case IFrameUpdateSystem iFrameUpdateSystem: + { + entitiesType = iFrameUpdateSystem.EntitiesType(); + _frameUpdateSystem.Add(entitiesType, iFrameUpdateSystem); + break; + } + default: + { + Log.Error($"IEntitiesSystem not support type {entitiesSystemType}"); + return; + } + } + + _assemblyList.Add(assemblyIdentity, entitiesType); + } + } + + private void OnUnLoadInner(long assemblyIdentity) + { + if (_assemblyHashCodes.TryGetValue(assemblyIdentity, out var entityType)) + { + foreach (var type in entityType) + { + _hashCodes.Remove(type); + } + + _assemblyHashCodes.RemoveByKey(assemblyIdentity); + } + + if (_assemblyList.TryGetValue(assemblyIdentity, out var assembly)) + { + foreach (var type in assembly) + { + _awakeSystems.Remove(type); + _updateSystems.Remove(type); + _destroySystems.Remove(type); + _deserializeSystems.Remove(type); + _frameUpdateSystem.Remove(type); + } + + _assemblyList.RemoveByKey(assemblyIdentity); + } + } + + #endregion + + #region Event + + /// + /// 触发实体的唤醒方法 + /// + /// 实体对象 + public void Awake(Entity entity) + { + if (!_awakeSystems.TryGetValue(entity.Type, out var awakeSystem)) + { + return; + } + + try + { + awakeSystem.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} Error {e}"); + } + } + + /// + /// 触发实体的销毁方法 + /// + /// 实体对象 + public void Destroy(Entity entity) + { + if (!_destroySystems.TryGetValue(entity.Type, out var system)) + { + return; + } + + try + { + system.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} Destroy Error {e}"); + } + } + + /// + /// 触发实体的反序列化方法 + /// + /// 实体对象 + public void Deserialize(Entity entity) + { + if (!_deserializeSystems.TryGetValue(entity.Type, out var system)) + { + return; + } + + try + { + system.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{entity.Type.FullName} Deserialize Error {e}"); + } + } + + #endregion + + #region Update + + /// + /// 将实体加入更新队列,准备进行更新 + /// + /// 实体对象 + public void StartUpdate(Entity entity) + { + var type = entity.Type; + var entityRuntimeId = entity.RuntimeId; + + if (_updateSystems.ContainsKey(type)) + { + var updateQueueInfo = new UpdateQueueInfo(type, entityRuntimeId); + _updateQueue.Enqueue(updateQueueInfo); + _updateQueueDic.Add(entityRuntimeId, updateQueueInfo); + } + + if (_frameUpdateSystem.ContainsKey(type)) + { + _frameUpdateQueue.Enqueue(new FrameUpdateQueueInfo(type, entityRuntimeId)); + } + } + + /// + /// 停止实体进行更新 + /// + /// 实体对象 + public void StopUpdate(Entity entity) + { + if (!_updateQueueDic.Remove(entity.RuntimeId, out var updateQueueInfo)) + { + return; + } + + updateQueueInfo.IsStop = true; + } + + /// + /// 执行实体系统的更新逻辑 + /// + public void Update() + { + var updateQueueCount = _updateQueue.Count; + + while (updateQueueCount-- > 0) + { + var updateQueueStruct = _updateQueue.Dequeue(); + + if (updateQueueStruct.IsStop) + { + continue; + } + + if (!_updateSystems.TryGetValue(updateQueueStruct.Type, out var updateSystem)) + { + continue; + } + + var entity = Scene.GetEntity(updateQueueStruct.RunTimeId); + + if (entity == null || entity.IsDisposed) + { + _updateQueueDic.Remove(updateQueueStruct.RunTimeId); + continue; + } + + _updateQueue.Enqueue(updateQueueStruct); + + try + { + updateSystem.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{updateQueueStruct.Type.FullName} Update Error {e}"); + } + } + } + + /// + /// 执行实体系统的帧更新逻辑 + /// + public void FrameUpdate() + { + var count = _frameUpdateQueue.Count; + + while (count-- > 0) + { + var frameUpdateQueueStruct = _frameUpdateQueue.Dequeue(); + + if (!_frameUpdateSystem.TryGetValue(frameUpdateQueueStruct.Type, out var frameUpdateSystem)) + { + continue; + } + + var entity = Scene.GetEntity(frameUpdateQueueStruct.RunTimeId); + + if (entity == null || entity.IsDisposed) + { + continue; + } + + _frameUpdateQueue.Enqueue(frameUpdateQueueStruct); + + try + { + frameUpdateSystem.Invoke(entity); + } + catch (Exception e) + { + Log.Error($"{frameUpdateQueueStruct.Type.FullName} FrameUpdate Error {e}"); + } + } + } + + #endregion + + public long GetHashCode(Type type) + { + return _hashCodes[type]; + } + + /// + /// 释放实体系统管理器资源 + /// + public override void Dispose() + { + _updateQueue.Clear(); + _frameUpdateQueue.Clear(); + + _assemblyList.Clear(); + _awakeSystems.Clear(); + _updateSystems.Clear(); + _destroySystems.Clear(); + _deserializeSystems.Clear(); + _frameUpdateSystem.Clear(); + + AssemblySystem.UnRegister(this); + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EntityComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EntityComponent.cs.meta new file mode 100644 index 00000000..a8384983 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EntityComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41c0ffdbeaaf84d848105eb341414c4a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent.meta new file mode 100644 index 00000000..e4535544 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5ff190d313de0433bb5c6cad4f116d1a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/EventComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/EventComponent.cs new file mode 100644 index 00000000..cbc667e6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/EventComponent.cs @@ -0,0 +1,253 @@ +using System; +using System.Reflection; +using Cysharp.Threading.Tasks; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; + +// ReSharper disable PossibleMultipleEnumeration +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +// ReSharper disable MethodOverloadWithOptionalParameter + +namespace Fantasy.Event +{ + internal sealed class EventCache + { + public readonly Type EnventType; + public readonly object Obj; + public EventCache(Type enventType, object obj) + { + EnventType = enventType; + Obj = obj; + } + } + + public sealed class EventComponent : Entity, IAssembly + { + private readonly OneToManyList _events = new(); + private readonly OneToManyList _asyncEvents = new(); + private readonly OneToManyList _assemblyEvents = new(); + private readonly OneToManyList _assemblyAsyncEvents = new(); + + internal async UniTask Initialize() + { + await AssemblySystem.Register(this); + return this; + } + + #region Assembly + + public async UniTask Load(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + await tcs.Task; + } + + public async UniTask ReLoad(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + await tcs.Task; + } + + public async UniTask OnUnLoad(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + await tcs.Task; + } + + private void LoadInner(long assemblyIdentity) + { + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IEvent))) + { + var @event = (IEvent)Activator.CreateInstance(type); + + if (@event == null) + { + continue; + } + + var eventType = @event.EventType(); + _events.Add(eventType, @event); + _assemblyEvents.Add(assemblyIdentity, new EventCache(eventType, @event)); + } + + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IAsyncEvent))) + { + var @event = (IAsyncEvent)Activator.CreateInstance(type); + + if (@event == null) + { + continue; + } + + var eventType = @event.EventType(); + _asyncEvents.Add(eventType, @event); + _assemblyAsyncEvents.Add(assemblyIdentity, new EventCache(eventType, @event)); + } + } + + private void OnUnLoadInner(long assemblyIdentity) + { + if (_assemblyEvents.TryGetValue(assemblyIdentity, out var events)) + { + foreach (var @event in events) + { + _events.RemoveValue(@event.EnventType, (IEvent)@event.Obj); + } + + _assemblyEvents.RemoveByKey(assemblyIdentity); + } + + if (_assemblyAsyncEvents.TryGetValue(assemblyIdentity, out var asyncEvents)) + { + foreach (var @event in asyncEvents) + { + _asyncEvents.RemoveValue(@event.EnventType, (IAsyncEvent)@event.Obj); + } + + _assemblyAsyncEvents.RemoveByKey(assemblyIdentity); + } + } + + #endregion + + #region Publish + + /// + /// 发布一个值类型的事件数据。 + /// + /// 事件数据类型(值类型)。 + /// 事件数据实例。 + public void Publish(TEventData eventData) where TEventData : struct + { + if (!_events.TryGetValue(typeof(TEventData), out var list)) + { + return; + } + + foreach (var @event in list) + { + try + { + @event.Invoke(eventData); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + /// + /// 发布一个继承自 Entity 的事件数据。 + /// + /// 事件数据类型(继承自 Entity)。 + /// 事件数据实例。 + /// 是否释放事件数据。 + public void Publish(TEventData eventData, bool isDisposed = true) where TEventData : Entity + { + if (!_events.TryGetValue(typeof(TEventData), out var list)) + { + return; + } + + foreach (var @event in list) + { + try + { + @event.Invoke(eventData); + } + catch (Exception e) + { + Log.Error(e); + } + } + + if (isDisposed) + { + eventData.Dispose(); + } + } + + /// + /// 异步发布一个值类型的事件数据。 + /// + /// 事件数据类型(值类型)。 + /// 事件数据实例。 + /// 表示异步操作的任务。 + public async UniTask PublishAsync(TEventData eventData) where TEventData : struct + { + if (!_asyncEvents.TryGetValue(typeof(TEventData), out var list)) + { + return; + } + + using var tasks = ListPool.Create(); + + foreach (var @event in list) + { + tasks.Add(@event.InvokeAsync(eventData)); + } + + await UniTask.WhenAll(tasks); + } + + /// + /// 异步发布一个继承自 Entity 的事件数据。 + /// + /// 事件数据类型(继承自 Entity)。 + /// 事件数据实例。 + /// 是否释放事件数据。 + /// 表示异步操作的任务。 + public async UniTask PublishAsync(TEventData eventData, bool isDisposed = true) where TEventData : Entity + { + if (!_asyncEvents.TryGetValue(eventData.GetType(), out var list)) + { + return; + } + + using var tasks = ListPool.Create(); + + foreach (var @event in list) + { + tasks.Add(@event.InvokeAsync(eventData)); + } + + await UniTask.WhenAll(tasks); + + if (isDisposed) + { + eventData.Dispose(); + } + } + + #endregion + + public override void Dispose() + { + _events.Clear(); + _asyncEvents.Clear(); + _assemblyEvents.Clear(); + _assemblyAsyncEvents.Clear(); + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta new file mode 100644 index 00000000..ac848069 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/EventComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc6c3f6b01eb14a35934175e36eeb544 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface.meta new file mode 100644 index 00000000..af3d4b86 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 10dcbb383d66a4915b44d6f20331a7bf +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs new file mode 100644 index 00000000..80f11648 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs @@ -0,0 +1,113 @@ +using System; +using Cysharp.Threading.Tasks; +using Fantasy.Async; + +namespace Fantasy.Event +{ + /// + /// 事件的接口 + /// + public interface IEvent + { + /// + /// 用于指定事件的Type + /// + /// + Type EventType(); + /// + /// 时间内部使用的入口 + /// + /// + void Invoke(object self); + } + + /// + /// 异步事件的接口 + /// + public interface IAsyncEvent + { + /// + /// + /// + /// + Type EventType(); + /// + /// + /// + /// + UniTask InvokeAsync(object self); + } + + /// + /// 事件的抽象类,要使用事件必须要继承这个抽象接口。 + /// + /// 要监听的事件泛型类型 + public abstract class EventSystem : IEvent + { + private readonly Type _selfType = typeof(T); + /// + /// + /// + /// + public Type EventType() + { + return _selfType; + } + /// + /// 事件调用的方法,要在这个方法里编写事件发生的逻辑 + /// + /// + protected abstract void Handler(T self); + /// + /// + /// + /// + public void Invoke(object self) + { + try + { + Handler((T) self); + } + catch (Exception e) + { + Log.Error($"{_selfType.Name} Error {e}"); + } + } + } + /// + /// 异步事件的抽象类,要使用事件必须要继承这个抽象接口。 + /// + /// 要监听的事件泛型类型 + public abstract class AsyncEventSystem : IAsyncEvent + { + private readonly Type _selfType = typeof(T); + /// + /// + /// + /// + public Type EventType() + { + return _selfType; + } + /// + /// 事件调用的方法,要在这个方法里编写事件发生的逻辑 + /// + /// + protected abstract UniTask Handler(T self); + /// + /// + /// + /// + public async UniTask InvokeAsync(object self) + { + try + { + await Handler((T) self); + } + catch (Exception e) + { + Log.Error($"{_selfType.Name} Error {e}"); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta new file mode 100644 index 00000000..5811d149 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/EventComponent/Interface/IEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e46ad748051f4277a8f660fa842b19d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/MessagePoolComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/MessagePoolComponent.cs new file mode 100644 index 00000000..f1ddb23a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/MessagePoolComponent.cs @@ -0,0 +1,139 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Pool; +using Fantasy.Serialize; + +namespace Fantasy.Entitas +{ + /// + /// 消息的对象池组件 + /// + public sealed class MessagePoolComponent : Entity + { + private int _poolCount; + private const int MaxCapacity = ushort.MaxValue; + private readonly OneToManyQueue _poolQueue = new OneToManyQueue(); + private readonly Dictionary> _typeCheckCache = new Dictionary>(); + /// + /// 销毁组件 + /// + public override void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + _typeCheckCache.Clear(); + base.Dispose(); + } + /// + /// 从对象池里获取一个消息,如果没有就创建一个新的 + /// + /// 消息的泛型类型 + /// + public T Rent() where T : AMessage, new() + { + if (!_poolQueue.TryDequeue(typeof(T), out var queue)) + { + var instance = new T(); + instance.SetScene(Scene); + instance.SetIsPool(true); + return instance; + } + + queue.SetIsPool(true); + _poolCount--; + return (T)queue; + } + + /// + /// + /// + /// 消息的类型 + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public AMessage Rent(Type type) + { + if (!_poolQueue.TryDequeue(type, out var queue)) + { + if (!_typeCheckCache.TryGetValue(type, out var createInstance)) + { + if (!typeof(AMessage).IsAssignableFrom(type)) + { + throw new NotSupportedException($"{this.GetType().FullName} Type:{type.FullName} must inherit from IPool"); + } + else + { + createInstance = CreateInstance.CreateMessage(type); + _typeCheckCache[type] = createInstance; + } + } + + var instance = createInstance(); + instance.SetScene(Scene); + instance.SetIsPool(true); + return instance; + } + + queue.SetIsPool(true); + _poolCount--; + return queue; + } + /// + /// 返还一个消息到对象池中 + /// + /// + public void Return(AMessage obj) + { + if (obj == null) + { + return; + } + + if (!obj.IsPool()) + { + return; + } + + if (_poolCount >= MaxCapacity) + { + return; + } + + _poolCount++; + obj.SetIsPool(false); + _poolQueue.Enqueue(obj.GetType(), obj); + } + + /// + /// + /// + /// 返还的消息 + /// 返还的消息泛型类型 + public void Return(T obj) where T : AMessage + { + if (obj == null) + { + return; + } + + if (!obj.IsPool()) + { + return; + } + + if (_poolCount >= MaxCapacity) + { + return; + } + + _poolCount++; + obj.SetIsPool(false); + _poolQueue.Enqueue(typeof(T), obj); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/MessagePoolComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/MessagePoolComponent.cs.meta new file mode 100644 index 00000000..a2ded96f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/MessagePoolComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4db4a3115fd64377b5b89f2bdc001a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent.meta new file mode 100644 index 00000000..d84b4bbe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3e4a6422ca1a44689a82bd9c788c8310 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs new file mode 100644 index 00000000..be82ee5c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs @@ -0,0 +1,168 @@ +// ReSharper disable SuspiciousTypeConversion.Global + +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#if FANTASY_NET +namespace Fantasy.SingleCollection +{ + /// + /// 用于处理Entity下的实体进行数据库分表存储的组件 + /// + public sealed class SingleCollectionComponent : Entity, IAssembly + { + private CoroutineLock _coroutineLock; + private readonly OneToManyHashSet _collection = new OneToManyHashSet(); + + private readonly OneToManyList _assemblyCollections = + new OneToManyList(); + + private sealed class SingleCollectionInfo(Type rootType, string collectionName) + { + public readonly Type RootType = rootType; + public readonly string CollectionName = collectionName; + } + + internal async FTask Initialize() + { + var coroutineLockType = HashCodeHelper.ComputeHash64(GetType().FullName); + _coroutineLock = Scene.CoroutineLockComponent.Create(coroutineLockType); + await AssemblySystem.Register(this); + return this; + } + + #region Assembly + + public async FTask Load(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask ReLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + public async FTask OnUnLoad(long assemblyIdentity) + { + var tcs = FTask.Create(false); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.SetResult(); + }); + await tcs; + } + + private void LoadInner(long assemblyIdentity) + { + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(ISupportedSingleCollection))) + { + var customAttributes = type.GetCustomAttributes(typeof(SingleCollectionAttribute), false); + if (customAttributes.Length == 0) + { + Log.Error( + $"type {type.FullName} Implemented the interface of ISingleCollection, requiring the implementation of SingleCollectionAttribute"); + continue; + } + + var singleCollectionAttribute = (SingleCollectionAttribute)customAttributes[0]; + var rootType = singleCollectionAttribute.RootType; + var collectionName = singleCollectionAttribute.CollectionName; + _collection.Add(rootType, collectionName); + _assemblyCollections.Add(assemblyIdentity, new SingleCollectionInfo(rootType, collectionName)); + } + } + + private void OnUnLoadInner(long assemblyIdentity) + { + if (!_assemblyCollections.TryGetValue(assemblyIdentity, out var types)) + { + return; + } + + foreach (var singleCollectionInfo in types) + { + _collection.RemoveValue(singleCollectionInfo.RootType, singleCollectionInfo.CollectionName); + } + + _assemblyCollections.RemoveByKey(assemblyIdentity); + } + + #endregion + + #region Collections + + /// + /// 通过数据库获取某一个实体类型下所有的分表数据到当前实体下,并且会自动建立父子关系。 + /// + /// 实体实例 + /// 实体泛型类型 + public async FTask GetCollections(T entity) where T : Entity, ISingleCollectionRoot + { + if (!_collection.TryGetValue(typeof(T), out var collections)) + { + return; + } + + var worldDateBase = Scene.World.DataBase; + + using (await _coroutineLock.Wait(entity.Id)) + { + foreach (var collectionName in collections) + { + var singleCollection = await worldDateBase.QueryNotLock(entity.Id, collectionName); + singleCollection.Deserialize(Scene); + entity.AddComponent(singleCollection); + } + } + } + + /// + /// 存储当前实体下支持分表的组件到数据中,包括存储实体本身。 + /// + /// 实体实例 + /// 实体泛型类型 + public async FTask SaveCollections(T entity) where T : Entity, ISingleCollectionRoot + { + using var collections = ListPool.Create(); + + foreach (var treeEntity in entity.ForEachSingleCollection) + { + if (treeEntity is not ISupportedSingleCollection) + { + continue; + } + + collections.Add(treeEntity); + } + + collections.Add(entity); + await entity.Scene.World.DataBase.Save(entity.Id, collections); + } + + #endregion + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta new file mode 100644 index 00000000..00f78d3b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/SingleCollectionComponent/SingleCollectionComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41291147b69444a6cb19ba948b421d2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent.meta new file mode 100644 index 00000000..e990774b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: de3b132dd12a0427face9541cc1ba095 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface.meta new file mode 100644 index 00000000..58c86172 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 20842cefeece84173bf625c41a94ef63 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs new file mode 100644 index 00000000..9e1f4c97 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs @@ -0,0 +1,10 @@ +using Fantasy.Event; + +namespace Fantasy.Timer +{ + /// + /// 计时器抽象类,提供了一个基础框架,用于创建处理计时器事件的具体类。 + /// + /// 事件的类型参数 + public abstract class TimerHandler : EventSystem { } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta new file mode 100644 index 00000000..cab3f9c2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/Interface/TimerHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0bb411c4d246b43aba54eb60b7654492 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel.meta new file mode 100644 index 00000000..8799bb84 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c29f20c4c348c4a2892df1702f14a9e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs new file mode 100644 index 00000000..d644386d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs @@ -0,0 +1,49 @@ +// #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// namespace Fantasy +// { +// public sealed class ScheduledTaskPool : PoolCore +// { +// public ScheduledTaskPool() : base(2000) { } +// +// public ScheduledTask Rent(Action action, ref int rounds, ref int finalSlot) +// { +// var scheduledTask = Rent(); +// scheduledTask.Rounds = rounds; +// scheduledTask.Action = action; +// scheduledTask.FinalSlot = finalSlot; +// return scheduledTask; +// } +// +// public override void Return(ScheduledTask item) +// { +// base.Return(item); +// item.Dispose(); +// } +// } +// +// public sealed class ScheduledTask : IPool, IDisposable +// { +// public int Rounds; +// public int FinalSlot; +// public Action Action; +// public LinkedListNode Node; +// +// public bool IsPool { get; set; } +// public ScheduledTask() { } +// public ScheduledTask(Action action, ref int rounds, ref int finalSlot) +// { +// Action = action; +// Rounds = rounds; +// FinalSlot = finalSlot; +// } +// +// public void Dispose() +// { +// Rounds = 0; +// FinalSlot = 0; +// Action = null; +// Node = null; +// } +// } +// } \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta new file mode 100644 index 00000000..4a73d852 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/ScheduledTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d711c8e49efac42c9bde8a1ff993b6f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs new file mode 100644 index 00000000..58916b14 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs @@ -0,0 +1,134 @@ +// using System.Runtime.CompilerServices; +// // ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// +// namespace Fantasy +// { +// public sealed class TimeWheel +// { +// private int _currentIndex; +// private ScheduledTaskPool _scheduledTaskPool; +// +// private readonly Scene _scene; +// private readonly int _wheelSize; +// private readonly int _tickDuration; +// private readonly TimeWheel _upperLevelWheel; +// private readonly LinkedList[] _wheel; +// private readonly Queue _tasksToReschedule = new Queue(); +// private readonly Dictionary _taskDictionary = new Dictionary(); +// +// public TimeWheel(TimerComponent timerComponent, int wheelSize, int tickDuration, TimeWheel upperLevelWheel = null) +// { +// _scene = timerComponent.Scene; +// _wheelSize = wheelSize; +// _tickDuration = tickDuration; +// _upperLevelWheel = upperLevelWheel; +// _scheduledTaskPool = timerComponent.ScheduledTaskPool; +// _wheel = new LinkedList[_wheelSize]; +// for (var i = 0; i < wheelSize; i++) +// { +// _wheel[i] = new LinkedList(); +// } +// } +// +// public long Schedule(Action action, int delay) +// { +// var ticks = delay / _tickDuration; +// var futureIndex = ticks + _currentIndex; +// var rounds = futureIndex / _wheelSize; +// var slot = futureIndex % _wheelSize; +// +// if (slot == 0) +// { +// slot = _wheelSize - 1; +// rounds--; +// } +// else +// { +// slot--; +// } +// +// var taskId = _scene.RuntimeIdFactory.Create; +// var task = _scheduledTaskPool.Rent(action, ref rounds, ref slot); +// task.Node = _wheel[slot].AddLast(task); +// _taskDictionary.Add(taskId, task); +// Console.WriteLine($"Schedule rounds:{rounds} slot:{slot} _currentIndex:{_currentIndex}"); +// return taskId; +// } +// +// public bool Remove(int taskId) +// { +// if (!_taskDictionary.TryGetValue(taskId, out var task)) +// { +// return false; +// } +// +// _taskDictionary.Remove(taskId); +// _wheel[task.FinalSlot].Remove(task.Node); +// _scheduledTaskPool.Return(task); +// Console.WriteLine("找到已经删除了任务"); +// return true; +// } +// +// public void Tick(object? state) +// { +// var currentWheel = _wheel[_currentIndex]; +// +// if (currentWheel.Count == 0) +// { +// AdvanceIndex(); +// return; +// } +// +// var currentNode = currentWheel.First; +// +// while (currentNode != null) +// { +// var nextNode = currentNode.Next; +// var task = currentNode.Value; +// +// if (task.Rounds <= 0 && task.FinalSlot == _currentIndex) +// { +// try +// { +// task.Action.Invoke(); +// } +// catch (Exception ex) +// { +// Log.Error($"Exception during task execution: {ex.Message}"); +// } +// } +// else +// { +// task.Rounds--; +// _tasksToReschedule.Enqueue(task); +// } +// +// currentWheel.Remove(currentNode); +// currentNode = nextNode; +// } +// +// RescheduleTasks(); +// AdvanceIndex(); +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private void AdvanceIndex() +// { +// _currentIndex = (_currentIndex + 1) % _wheelSize; +// if (_currentIndex == 0 && _upperLevelWheel != null) +// { +// _upperLevelWheel.Tick(null); +// } +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private void RescheduleTasks() +// { +// while (_tasksToReschedule.TryDequeue(out var task)) +// { +// _wheel[task.FinalSlot].AddLast(task); +// } +// } +// } +// } \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta new file mode 100644 index 00000000..bc71944c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimeWheel/TimeWheel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 362cc9ecb907d45129e4fdff9ef87039 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerAction.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerAction.cs new file mode 100644 index 00000000..2a836ab6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerAction.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 +#pragma warning disable CS8618 + +namespace Fantasy.Timer +{ + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct TimerAction + { + public long TimerId; + public long StartTime; + public long TriggerTime; + public readonly object Callback; + public readonly TimerType TimerType; + public TimerAction(long timerId, TimerType timerType, long startTime, long triggerTime, object callback) + { + TimerId = timerId; + Callback = callback; + TimerType = timerType; + StartTime = startTime; + TriggerTime = triggerTime; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta new file mode 100644 index 00000000..6da3670a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerAction.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c875fd82f74f430c963315b79f7a9a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerComponent.cs new file mode 100644 index 00000000..ffa7864f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerComponent.cs @@ -0,0 +1,52 @@ +// ReSharper disable ForCanBeConvertedToForeach + +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#if FANTASY_UNITY +using UnityEngine; +#endif +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Timer +{ + public sealed class TimerComponentUpdateSystem : UpdateSystem + { + protected override void Update(TimerComponent self) + { + self.Update(); + } + } + + /// + /// 时间调度组件 + /// + public sealed class TimerComponent : Entity + { + /// + /// 使用系统时间创建的计时器核心。 + /// + public TimerSchedulerNet Net { get; private set; } +#if FANTASY_UNITY + /// + /// 使用 Unity 时间创建的计时器核心。 + /// + public TimerSchedulerNetUnity Unity { get; private set; } +#endif + internal TimerComponent Initialize() + { + Net = new TimerSchedulerNet(Scene); +#if FANTASY_UNITY + Unity = new TimerSchedulerNetUnity(Scene); +#endif + return this; + } + public void Update() + { + Net.Update(); +#if FANTASY_UNITY + Unity.Update(); +#endif + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta new file mode 100644 index 00000000..32b51016 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b33402f4024349359a173ef6aa46abf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta new file mode 100644 index 00000000..d4294c1c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 74544bc3e0a9a4cc2af251a9a2a871c1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs new file mode 100644 index 00000000..ef3aaf0d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs @@ -0,0 +1,393 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Helper; +// ReSharper disable UnusedParameter.Global + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.Timer +{ + /// + /// 基于系统事件的任务调度系统 + /// + public sealed class TimerSchedulerNet + { + private readonly Scene _scene; + private long _idGenerator; + private long _minTime; // 最小时间 + private readonly Queue _timeOutTime = new Queue(); + private readonly Queue _timeOutTimerIds = new Queue(); + private readonly Dictionary _timerActions = new Dictionary(); + private readonly SortedOneToManyList _timeId = new(); // 时间与计时器ID的有序一对多列表 + private long GetId => ++_idGenerator; + /// + /// 构造函数 + /// + /// 当前的Scene + public TimerSchedulerNet(Scene scene) + { + _scene = scene; + } + + private long Now() + { + return TimeHelper.Now; + } + + /// + /// 驱动方法,只有调用这个方法任务系统才会正常运转。 + /// + public void Update() + { + if (_timeId.Count == 0) + { + return; + } + + var currentTime = Now(); + + if (currentTime < _minTime) + { + return; + } + + // 遍历时间ID列表,查找超时的计时器任务 + foreach (var (key, _) in _timeId) + { + if (key > currentTime) + { + _minTime = key; + break; + } + + _timeOutTime.Enqueue(key); + } + + // 处理超时的计时器任务 + while (_timeOutTime.TryDequeue(out var time)) + { + var timerIds = _timeId[time]; + for (var i = 0; i < timerIds.Count; ++i) + { + _timeOutTimerIds.Enqueue(timerIds[i]); + } + + _timeId.Remove(time); + // _timeId.RemoveKey(time); + } + + if (_timeId.Count == 0) + { + _minTime = long.MaxValue; + } + + // 执行超时的计时器任务的回调操作 + while (_timeOutTimerIds.TryDequeue(out var timerId)) + { + if (!_timerActions.Remove(timerId, out var timerAction)) + { + continue; + } + + // 根据计时器类型执行不同的操作 + switch (timerAction.TimerType) + { + case TimerType.OnceWaitTimer: + { + var tcs = (AutoResetUniTaskCompletionSourcePlus)timerAction.Callback; + tcs.TrySetResult(true); + break; + } + case TimerType.OnceTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + action(); + break; + } + case TimerType.RepeatedTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + timerAction.StartTime = Now(); + AddTimer(ref timerAction); + action(); + break; + } + } + } + } + + private void AddTimer(ref TimerAction timer) + { + var tillTime = timer.StartTime + timer.TriggerTime; + _timeId.Add(tillTime, timer.TimerId); + _timerActions.Add(timer.TimerId, timer); + + if (tillTime < _minTime) + { + _minTime = tillTime; + } + } + + /// + /// 异步等待指定时间。 + /// + /// 等待的时间长度。 + /// 取消令牌。 + /// 等待是否成功。 + public async UniTask WaitAsync(long time, CancellationToken cancellationToken = default) + { + if (time <= 0) + { + return true; + } + + var now = Now(); + var timerId = GetId; + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, time, tcs); + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.TrySetResult(false); + } + } + + bool result; + + try + { + tcs?.AddOnCancelAction(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs.Task; + } + finally + { + tcs?.RemoveOnCancelAction(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待直到指定时间。 + /// + /// 等待的目标时间。 + /// 取消令牌。 + /// 等待是否成功。 + public async UniTask WaitTillAsync(long tillTime, CancellationToken cancellationToken = default) + { + var now = Now(); + + if (now >= tillTime) + { + return true; + } + + var timerId = GetId; + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, tillTime - now, tcs); + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.TrySetResult(false); + } + } + + bool result; + + try + { + tcs?.AddOnCancelAction(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs.Task; + } + finally + { + tcs?.RemoveOnCancelAction(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待一帧时间。 + /// + /// 等待是否成功。 + public async UniTask WaitFrameAsync() + { +#if FANTASY_NET + await WaitAsync(100); +#else + await WaitAsync(1); +#endif + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// + public long OnceTimer(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, Action action) + { + var now = Now(); + + if (tillTime < now) + { + Log.Error($"new once time too small tillTime:{tillTime} Now:{now}"); + } + + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, tillTime - now, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的延迟时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTimer(long time, T timerHandlerType) where T : struct + { + void OnceTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTimer(time, OnceTimerVoid); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的目标时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, T timerHandlerType) where T : struct + { + void OnceTillTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTillTimer(tillTime, OnceTillTimerVoid); + } + + /// + /// 创建一个帧任务 + /// + /// + /// + public long FrameTimer(Action action) + { +#if FANTASY_NET + return RepeatedTimerInner(100, action); +#else + return RepeatedTimerInner(0, action); +#endif + } + + /// + /// 创建一个重复执行的计时器。 + /// + /// 计时器重复间隔的时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, Action action) + { + if (time < 0) + { + Log.Error($"time too small: {time}"); + return 0; + } + + return RepeatedTimerInner(time, action); + } + + /// + /// 创建一个重复执行的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器重复间隔的时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, T timerHandlerType) where T : struct + { + void RepeatedTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return RepeatedTimer(time, RepeatedTimerVoid); + } + + private long RepeatedTimerInner(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.RepeatedTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// + /// + public bool Remove(ref long timerId) + { + var id = timerId; + timerId = 0; + return Remove(id); + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// 计时器的 ID。 + public bool Remove(long timerId) + { + return timerId != 0 && _timerActions.Remove(timerId, out _); + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta new file mode 100644 index 00000000..c9f6027d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: af9a02de83dce4c088f786cf6cf6bdd7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs new file mode 100644 index 00000000..377607d3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs @@ -0,0 +1,372 @@ +#if FANTASY_UNITY +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Helper; +using UnityEngine; +namespace Fantasy.Timer +{ + public sealed class TimerSchedulerNetUnity + { + private readonly Scene _scene; + private long _idGenerator; + private long _minTime; // 最小时间 + private readonly Queue _timeOutTime = new Queue(); + private readonly Queue _timeOutTimerIds = new Queue(); + private readonly Dictionary _timerActions = new Dictionary(); + private readonly SortedOneToManyList _timeId = new(); // 时间与计时器ID的有序一对多列表 + private long GetId => ++_idGenerator; + public TimerSchedulerNetUnity(Scene scene) + { + _scene = scene; + } + + private long Now() + { + return (long)(Time.time * 1000); + } + + public void Update() + { + if (_timeId.Count == 0) + { + return; + } + + var currentTime = Now(); + + if (currentTime < _minTime) + { + return; + } + + // 遍历时间ID列表,查找超时的计时器任务 + foreach (var (key, _) in _timeId) + { + if (key > currentTime) + { + _minTime = key; + break; + } + + _timeOutTime.Enqueue(key); + } + + // 处理超时的计时器任务 + while (_timeOutTime.TryDequeue(out var time)) + { + var timerIds = _timeId[time]; + for (var i = 0; i < timerIds.Count; ++i) + { + _timeOutTimerIds.Enqueue(timerIds[i]); + } + + _timeId.Remove(time); + // _timeId.RemoveKey(time); + } + + if (_timeId.Count == 0) + { + _minTime = long.MaxValue; + } + + // 执行超时的计时器任务的回调操作 + while (_timeOutTimerIds.TryDequeue(out var timerId)) + { + if (!_timerActions.Remove(timerId, out var timerAction)) + { + continue; + } + + // 根据计时器类型执行不同的操作 + switch (timerAction.TimerType) + { + case TimerType.OnceWaitTimer: + { + var tcs = (AutoResetUniTaskCompletionSourcePlus)timerAction.Callback; + tcs.TrySetResult(true); + break; + } + case TimerType.OnceTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + action(); + break; + } + case TimerType.RepeatedTimer: + { + if (timerAction.Callback is not Action action) + { + Log.Error($"timerAction {timerAction.ToJson()}"); + break; + } + + timerAction.StartTime = Now(); + AddTimer(ref timerAction); + action(); + break; + } + } + } + } + + private void AddTimer(ref TimerAction timer) + { + var tillTime = timer.StartTime + timer.TriggerTime; + _timeId.Add(tillTime, timer.TimerId); + _timerActions.Add(timer.TimerId, timer); + + if (tillTime < _minTime) + { + _minTime = tillTime; + } + } + + /// + /// 异步等待指定时间。 + /// + /// 等待的时间长度。 + /// 等待是否成功。 + public async UniTask WaitAsync(long time) + { + if (time <= 0) + { + return true; + } + + var now = Now(); + var timerId = GetId; + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, time, tcs); + + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.TrySetResult(false); + } + } + + bool result; + + try + { + tcs.AddOnCancelAction(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs.Task; + } + finally + { + tcs.RemoveOnCancelAction(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待直到指定时间。 + /// + /// 等待的目标时间。 + /// 等待是否成功。 + public async UniTask WaitTillAsync(long tillTime) + { + var now = Now(); + + if (now >= tillTime) + { + return true; + } + + var timerId = GetId; + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + var timerAction = new TimerAction(timerId, TimerType.OnceWaitTimer, now, tillTime - now, tcs); + + void CancelActionVoid() + { + if (Remove(timerId)) + { + tcs.TrySetResult(false); + } + } + + bool result; + + try + { + tcs.AddOnCancelAction(CancelActionVoid); + AddTimer(ref timerAction); + result = await tcs.Task; + } + finally + { + tcs.RemoveOnCancelAction(CancelActionVoid); + } + + return result; + } + + /// + /// 异步等待一帧时间。 + /// + /// 等待是否成功。 + public async UniTask WaitFrameAsync(CancellationToken cancellationToken = default) + { + await UniTask.NextFrame(cancellationToken); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// + public long OnceTimer(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间。 + /// + /// 计时器执行的目标时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, Action action) + { + var now = Now(); + + if (tillTime < now) + { + Log.Error($"new once time too small tillTime:{tillTime} Now:{now}"); + } + + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.OnceTimer, now, tillTime - now, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 创建一个只执行一次的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的延迟时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTimer(long time, T timerHandlerType) where T : struct + { + void OnceTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTimer(time, OnceTimerVoid); + } + + /// + /// 创建一个只执行一次的计时器,直到指定时间,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器执行的目标时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long OnceTillTimer(long tillTime, T timerHandlerType) where T : struct + { + void OnceTillTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return OnceTillTimer(tillTime, OnceTillTimerVoid); + } + + /// + /// 创建一个帧任务 + /// + /// + /// + public long FrameTimer(Action action) + { + return RepeatedTimerInner(1, action); + } + + /// + /// 创建一个重复执行的计时器。 + /// + /// 计时器重复间隔的时间。 + /// 计时器回调方法。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, Action action) + { + if (time < 0) + { + Log.Error($"time too small: {time}"); + return 0; + } + + return RepeatedTimerInner(time, action); + } + + /// + /// 创建一个重复执行的计时器,用于发布指定类型的事件。 + /// + /// 事件类型。 + /// 计时器重复间隔的时间。 + /// 事件处理器类型。 + /// 计时器的 ID。 + public long RepeatedTimer(long time, T timerHandlerType) where T : struct + { + void RepeatedTimerVoid() + { + _scene.EventComponent.Publish(timerHandlerType); + } + + return RepeatedTimer(time, RepeatedTimerVoid); + } + + private long RepeatedTimerInner(long time, Action action) + { + var now = Now(); + var timerId = GetId; + var timerAction = new TimerAction(timerId, TimerType.RepeatedTimer, now, time, action); + AddTimer(ref timerAction); + return timerId; + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// + /// + public bool Remove(ref long timerId) + { + var id = timerId; + timerId = 0; + return Remove(id); + } + + /// + /// 移除指定 ID 的计时器。 + /// + /// 计时器的 ID。 + public bool Remove(long timerId) + { + return timerId != 0 && _timerActions.Remove(timerId, out _); + } + } +} +#endif + diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta new file mode 100644 index 00000000..a5e25396 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerScheduler/TimerSchedulerNetUnity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d14712dd51d84d7eb7e8998013d28ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerType.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerType.cs new file mode 100644 index 00000000..6f16f806 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerType.cs @@ -0,0 +1,25 @@ +namespace Fantasy.Timer +{ + /// + /// 枚举对象TimerType + /// + public enum TimerType + { + /// + /// None + /// + None, + /// + /// 一次等待定时器 + /// + OnceWaitTimer, + /// + /// 一次性定时器 + /// + OnceTimer, + /// + /// 重复定时器 + /// + RepeatedTimer + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta new file mode 100644 index 00000000..b0985725 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Component/TimerComponent/TimerType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b1b471e1861ac4718a57e94ba520588e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Entity.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Entity.cs new file mode 100644 index 00000000..a5adf92d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Entity.cs @@ -0,0 +1,1046 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using Fantasy.Async; +using Fantasy.Entitas.Interface; +using Fantasy.Pool; +using Fantasy.Serialize; +using MongoDB.Bson.Serialization.Attributes; +using Newtonsoft.Json; +using ProtoBuf; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable MergeIntoPattern +// ReSharper disable SuspiciousTypeConversion.Global +// ReSharper disable NullCoalescingConditionIsAlwaysNotNullAccordingToAPIContract +// ReSharper disable CheckNamespace +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Entitas +{ + /// + /// 用来表示一个Entity + /// + public interface IEntity : IDisposable, IPool { } + + /// + /// Entity的抽象类,任何Entity必须继承这个接口才可以使用 + /// + public abstract partial class Entity : IEntity + { + #region Members + + /// + /// 获取一个值,表示实体是否支持对象池。 + /// + [BsonIgnore] + [JsonIgnore] + [ProtoIgnore] + [IgnoreDataMember] + private bool _isPool; + /// + /// 实体的Id + /// + [BsonId] + [BsonElement] + [BsonIgnoreIfDefault] + [BsonDefaultValue(0L)] + public long Id { get; protected set; } + /// + /// 实体的RunTimeId,其他系统可以通过这个Id发送Route消息,这个Id也可以理解为RouteId + /// + [BsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public long RuntimeId { get; protected set; } + /// + /// 当前实体是否已经被销毁 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public bool IsDisposed => RuntimeId == 0; + /// + /// 当前实体所归属的Scene + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public Scene Scene { get; protected set; } + /// + /// 实体的父实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public Entity Parent { get; protected set; } + /// + /// 实体的真实Type + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public Type Type { get; protected set; } +#if FANTASY_NET + [BsonElement("t")] [BsonIgnoreIfNull] private EntityList _treeDb; + [BsonElement("m")] [BsonIgnoreIfNull] private EntityList _multiDb; +#endif + [BsonIgnore] [IgnoreDataMember] [ProtoIgnore] private EntitySortedDictionary _tree; + [BsonIgnore] [IgnoreDataMember] [ProtoIgnore] private EntitySortedDictionary _multi; + + /// + /// 获得父Entity + /// + /// 父实体的泛型类型 + /// + public T GetParent() where T : Entity, new() + { + return Parent as T; + } + + #endregion + + #region Create + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 实体的Type + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// + public static Entity Create(Scene scene, Type type, bool isPool, bool isRunEvent) + { + return Create(scene, type, scene.EntityIdFactory.Create, isPool, isRunEvent); + } + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 实体的Type + /// 指定实体的Id + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// + public static Entity Create(Scene scene, Type type, long id, bool isPool, bool isRunEvent) + { + if (!typeof(Entity).IsAssignableFrom(type)) + { + throw new NotSupportedException($"{type.FullName} Type:{type.FullName} must inherit from Entity"); + } + + Entity entity = null; + + if (isPool) + { + entity = (Entity)scene.EntityPool.Rent(type); + } + else + { + if (!scene.TypeInstance.TryGetValue(type, out var createInstance)) + { + createInstance = CreateInstance.CreateIPool(type); + scene.TypeInstance[type] = createInstance; + } + + entity = (Entity)createInstance(); + } + + entity.Scene = scene; + entity.Type = type; + entity.SetIsPool(isPool); + entity.Id = id; + entity.RuntimeId = scene.RuntimeIdFactory.Create; + scene.AddEntity(entity); + + if (isRunEvent) + { + scene.EntityComponent.Awake(entity); + scene.EntityComponent.StartUpdate(entity); + } + + return entity; + } + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// 要创建的实体泛型类型 + /// + public static T Create(Scene scene, bool isPool, bool isRunEvent) where T : Entity, new() + { + return Create(scene, scene.EntityIdFactory.Create, isPool, isRunEvent); + } + + /// + /// 创建一个实体 + /// + /// 所属的Scene + /// 指定实体的Id + /// 是否从对象池创建,如果选择的是,销毁的时候同样会进入对象池 + /// 是否执行实体事件 + /// 要创建的实体泛型类型 + /// + public static T Create(Scene scene, long id, bool isPool, bool isRunEvent) where T : Entity, new() + { + var entity = isPool ? scene.EntityPool.Rent() : new T(); + entity.Scene = scene; + entity.Type = typeof(T); + entity.SetIsPool(isPool); + entity.Id = id; + entity.RuntimeId = scene.RuntimeIdFactory.Create; + scene.AddEntity(entity); + + if (isRunEvent) + { + scene.EntityComponent.Awake(entity); + scene.EntityComponent.StartUpdate(entity); + } + + return entity; + } + + #endregion + + #region AddComponent + + /// + /// 添加一个组件到当前实体上 + /// + /// 是否从对象池里创建 + /// 要添加组件的泛型类型 + /// 返回添加到实体上组件的实例 + public T AddComponent(bool isPool = true) where T : Entity, new() + { + var id = SupportedMultiEntityChecker.IsSupported ? Scene.EntityIdFactory.Create : Id; + var entity = Create(Scene, id, isPool, false); + AddComponent(entity); + Scene.EntityComponent.Awake(entity); + Scene.EntityComponent.StartUpdate(entity); + return entity; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 要添加组件的Id + /// 是否从对象池里创建 + /// 要添加组件的泛型类型 + /// 返回添加到实体上组件的实例 + public T AddComponent(long id, bool isPool = true) where T : Entity, new() + { + var entity = Create(Scene, id, isPool, false); + AddComponent(entity); + Scene.EntityComponent.Awake(entity); + Scene.EntityComponent.StartUpdate(entity); + return entity; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 要添加的实体实例 + public void AddComponent(Entity component) + { + if (this == component) + { + Log.Error("Cannot add oneself to one's own components"); + return; + } + + if (component.IsDisposed) + { + Log.Error($"component is Disposed {component.Type.FullName}"); + return; + } + + var type = component.Type; + component.Parent?.RemoveComponent(component, false); + + if (component is ISupportedMultiEntity) + { + _multi ??= Scene.EntitySortedDictionaryPool.Rent(); + _multi.Add(component.Id, component); +#if FANTASY_NET + if (component is ISupportedDataBase) + { + _multiDb ??= Scene.EntityListPool.Rent(); + _multiDb.Add(component); + } +#endif + } + else + { +#if FANTASY_NET + if (component is ISupportedSingleCollection && component.Id != Id) + { + Log.Error($"component type :{type.FullName} for implementing ISupportedSingleCollection, it is required that the Id must be the same as the parent"); + } +#endif + var typeHashCode = Scene.EntityComponent.GetHashCode(type);; + + if (_tree == null) + { + _tree = Scene.EntitySortedDictionaryPool.Rent(); + } + else if (_tree.ContainsKey(typeHashCode)) + { + Log.Error($"type:{type.FullName} If you want to add multiple components of the same type, please implement IMultiEntity"); + return; + } + + _tree.Add(typeHashCode, component); +#if FANTASY_NET + if (component is ISupportedDataBase) + { + _treeDb ??= Scene.EntityListPool.Rent(); + _treeDb.Add(component); + } +#endif + } + + component.Parent = this; + component.Scene = Scene; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 要添加的实体实例 + /// 要添加组件的泛型类型 + public void AddComponent(T component) where T : Entity + { + var type = typeof(T); + + if (type == typeof(Entity)) + { + Log.Error("Cannot add a generic Entity type as a component. Specify a more specific type."); + return; + } + + if (this == component) + { + Log.Error("Cannot add oneself to one's own components"); + return; + } + + if (component.IsDisposed) + { + Log.Error($"component is Disposed {type.FullName}"); + return; + } + + component.Parent?.RemoveComponent(component, false); + + if (SupportedMultiEntityChecker.IsSupported) + { + _multi ??= Scene.EntitySortedDictionaryPool.Rent(); + _multi.Add(component.Id, component); +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _multiDb ??= Scene.EntityListPool.Rent(); + _multiDb.Add(component); + } +#endif + } + else + { +#if FANTASY_NET + if (SupportedSingleCollectionChecker.IsSupported && component.Id != Id) + { + Log.Error($"component type :{type.FullName} for implementing ISupportedSingleCollection, it is required that the Id must be the same as the parent"); + } +#endif + var typeHashCode = Scene.EntityComponent.GetHashCode(type); + + if (_tree == null) + { + _tree = Scene.EntitySortedDictionaryPool.Rent(); + } + else if (_tree.ContainsKey(typeHashCode)) + { + Log.Error($"type:{type.FullName} If you want to add multiple components of the same type, please implement IMultiEntity"); + return; + } + + _tree.Add(typeHashCode, component); +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _treeDb ??= Scene.EntityListPool.Rent(); + _treeDb.Add(component); + } +#endif + } + + component.Parent = this; + component.Scene = Scene; + } + + /// + /// 添加一个组件到当前实体上 + /// + /// 组件的类型 + /// 是否在对象池创建 + /// + public Entity AddComponent(Type type, bool isPool = true) + { + var id = typeof(ISupportedMultiEntity).IsAssignableFrom(type) ? Scene.EntityIdFactory.Create : Id; + var entity = Entity.Create(Scene, type, id, isPool, false); + AddComponent(entity); + Scene.EntityComponent.Awake(entity); + Scene.EntityComponent.StartUpdate(entity); + return entity; + } + + #endregion + + #region HasComponent + + /// + /// 当前实体上是否有指定类型的组件 + /// + /// + /// + public bool HasComponent() where T : Entity, new() + { + return HasComponent(typeof(T)); + } + + /// + /// 当前实体上是否有指定类型的组件 + /// + /// + /// + public bool HasComponent(Type type) + { + if (_tree == null) + { + return false; + } + + return _tree.ContainsKey(Scene.EntityComponent.GetHashCode(type)); + } + + /// + /// 当前实体上是否有指定类型的组件 + /// + /// + /// + /// + public bool HasComponent(long id) where T : Entity, ISupportedMultiEntity, new() + { + if (_multi == null) + { + return false; + } + + return _multi.ContainsKey(id); + } + + #endregion + + #region GetComponent + + /// + /// 当前实体上查找一个字实体 + /// + /// 要查找实体泛型类型 + /// 查找的实体实例 + public T GetComponent() where T : Entity, new() + { + if (_tree == null) + { + return null; + } + + var typeHashCode = Scene.EntityComponent.GetHashCode(typeof(T)); + return _tree.TryGetValue(typeHashCode, out var component) ? (T)component : null; + } + + /// + /// 当前实体上查找一个字实体 + /// + /// 要查找实体类型 + /// 查找的实体实例 + public Entity GetComponent(Type type) + { + if (_tree == null) + { + return null; + } + + var typeHashCode = Scene.EntityComponent.GetHashCode(type); + return _tree.TryGetValue(typeHashCode, out var component) ? component : null; + } + + /// + /// 当前实体上查找一个字实体 + /// + /// 要查找实体的Id + /// 要查找实体泛型类型 + /// 查找的实体实例 + public T GetComponent(long id) where T : Entity, ISupportedMultiEntity, new() + { + if (_multi == null) + { + return default; + } + + return _multi.TryGetValue(id, out var entity) ? (T)entity : default; + } + + /// + /// 当前实体上查找一个字实体,如果没有就创建一个新的并添加到当前实体上 + /// + /// 是否从对象池创建 + /// 要查找或添加实体泛型类型 + /// 查找的实体实例 + public T GetOrAddComponent(bool isPool = true) where T : Entity, new() + { + return GetComponent() ?? AddComponent(isPool); + } + + #endregion + + #region RemoveComponent + + /// + /// 当前实体下删除一个实体 + /// + /// 是否执行删除实体的Dispose方法 + /// 实体的泛型类型 + /// + public void RemoveComponent(bool isDispose = true) where T : Entity, new() + { + if (SupportedMultiEntityChecker.IsSupported) + { + throw new NotSupportedException($"{typeof(T).FullName} message:Cannot delete components that implement the ISupportedMultiEntity interface"); + } + + if (_tree == null) + { + return; + } + + var type = typeof(T); + var typeHashCode = Scene.EntityComponent.GetHashCode(type); + if (!_tree.TryGetValue(typeHashCode, out var component)) + { + return; + } +#if FANTASY_NET + if (_treeDb != null && SupportedDataBaseChecker.IsSupported) + { + _treeDb.Remove(component); + + if (_treeDb.Count == 0) + { + Scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + } +#endif + _tree.Remove(typeHashCode); + + if (_tree.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + + if (isDispose) + { + component.Dispose(); + } + } + + /// + /// 当前实体下删除一个实体 + /// + /// 要删除的实体Id + /// 是否执行删除实体的Dispose方法 + /// 实体的泛型类型 + public void RemoveComponent(long id, bool isDispose = true) where T : Entity, ISupportedMultiEntity, new() + { + if (_multi == null) + { + return; + } + + if (!_multi.TryGetValue(id, out var component)) + { + return; + } +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _multiDb.Remove(component); + if (_multiDb.Count == 0) + { + Scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } + } +#endif + _multi.Remove(component.Id); + if (_multi.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } + + if (isDispose) + { + component.Dispose(); + } + } + + /// + /// 当前实体下删除一个实体 + /// + /// 要删除的实体实例 + /// 是否执行删除实体的Dispose方法 + public void RemoveComponent(Entity component, bool isDispose = true) + { + if (this == component) + { + return; + } + + if (component is ISupportedMultiEntity) + { + if (_multi != null) + { + if (!_multi.ContainsKey(component.Id)) + { + return; + } +#if FANTASY_NET + if (component is ISupportedDataBase) + { + _multiDb.Remove(component); + if (_multiDb.Count == 0) + { + Scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } + } +#endif + _multi.Remove(component.Id); + if (_multi.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } + } + } + else if (_tree != null) + { + var typeHashCode = Scene.EntityComponent.GetHashCode(component.Type); + if (!_tree.ContainsKey(typeHashCode)) + { + return; + } +#if FANTASY_NET + if (_treeDb != null && component is ISupportedDataBase) + { + _treeDb.Remove(component); + + if (_treeDb.Count == 0) + { + Scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + } +#endif + _tree.Remove(typeHashCode); + + if (_tree.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + } + + if (isDispose) + { + component.Dispose(); + } + } + + /// + /// 当前实体下删除一个实体 + /// + /// 要删除的实体实例 + /// 是否执行删除实体的Dispose方法 + /// 实体的泛型类型 + public void RemoveComponent(T component, bool isDispose = true) where T : Entity + { + if (this == component) + { + return; + } + + if (typeof(T) == typeof(Entity)) + { + Log.Error("Cannot remove a generic Entity type as a component. Specify a more specific type."); + return; + } + + if (SupportedMultiEntityChecker.IsSupported) + { + if (_multi != null) + { + if (!_multi.ContainsKey(component.Id)) + { + return; + } +#if FANTASY_NET + if (SupportedDataBaseChecker.IsSupported) + { + _multiDb.Remove(component); + if (_multiDb.Count == 0) + { + Scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } + } +#endif + _multi.Remove(component.Id); + if (_multi.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } + } + } + else if (_tree != null) + { + var typeHashCode = Scene.EntityComponent.GetHashCode(typeof(T)); + if (!_tree.ContainsKey(typeHashCode)) + { + return; + } +#if FANTASY_NET + if (_treeDb != null && SupportedDataBaseChecker.IsSupported) + { + _treeDb.Remove(component); + + if (_treeDb.Count == 0) + { + Scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + } +#endif + _tree.Remove(typeHashCode); + + if (_tree.Count == 0) + { + Scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + } + + if (isDispose) + { + component.Dispose(); + } + } + + #endregion + + #region Deserialize + + /// + /// 反序列化当前实体,因为在数据库加载过来的或通过协议传送过来的实体并没有跟当前Scene做关联。 + /// 所以必须要执行一下这个反序列化的方法才可以使用。 + /// + /// Scene + /// 是否是重新生成实体的Id,如果是数据库加载过来的一般是不需要的 + public void Deserialize(Scene scene, bool resetId = false) + { + if (RuntimeId != 0) + { + return; + } + + try + { + Scene = scene; + Type ??= GetType(); + RuntimeId = Scene.RuntimeIdFactory.Create; + if (resetId) + { + Id = RuntimeId; + } +#if FANTASY_NET + if (_treeDb != null && _treeDb.Count > 0) + { + _tree = Scene.EntitySortedDictionaryPool.Rent(); + foreach (var entity in _treeDb) + { + entity.Parent = this; + entity.Type = entity.GetType(); + var typeHashCode = Scene.EntityComponent.GetHashCode(entity.Type); + _tree.Add(typeHashCode, entity); + entity.Deserialize(scene, resetId); + } + } + + if (_multiDb != null && _multiDb.Count > 0) + { + _multi = Scene.EntitySortedDictionaryPool.Rent(); + foreach (var entity in _multiDb) + { + entity.Parent = this; + entity.Deserialize(scene, resetId); + _multi.Add(entity.Id, entity); + } + } +#endif + scene.AddEntity(this); + scene.EntityComponent.Deserialize(this); + } + catch (Exception e) + { + if (RuntimeId != 0) + { + scene.RemoveEntity(RuntimeId); + } + + Log.Error(e); + } + } + + #endregion + + #region ForEach +#if FANTASY_NET + /// + /// 查询当前实体下支持数据库分表存储实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachSingleCollection + { + get + { + foreach (var (_, treeEntity) in _tree) + { + if (treeEntity is not ISupportedSingleCollection) + { + continue; + } + + yield return treeEntity; + } + } + } + /// + /// 查询当前实体下支持传送实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachTransfer + { + get + { + if (_tree != null) + { + foreach (var (_, treeEntity) in _tree) + { + if (treeEntity is ISupportedTransfer) + { + yield return treeEntity; + } + } + } + + if (_multiDb != null) + { + foreach (var treeEntity in _multiDb) + { + if (treeEntity is not ISupportedTransfer) + { + continue; + } + + yield return treeEntity; + } + } + } + } +#endif + /// + /// 查询当前实体下的实现了ISupportedMultiEntity接口的实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachMultiEntity + { + get + { + if (_multi == null) + { + yield break; + } + + foreach (var (_, supportedMultiEntity) in _multi) + { + yield return supportedMultiEntity; + } + } + } + /// + /// 查找当前实体下的所有实体,不包括实现ISupportedMultiEntity接口的实体 + /// + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + public IEnumerable ForEachEntity + { + get + { + if (_tree == null) + { + yield break; + } + + foreach (var (_, entity) in _tree) + { + yield return entity; + } + } + } + #endregion + + #region Dispose + + /// + /// 销毁当前实体,销毁后会自动销毁当前实体下的所有实体。 + /// + public virtual void Dispose() + { + if (IsDisposed) + { + return; + } + + var scene = Scene; + var runTimeId = RuntimeId; + RuntimeId = 0; + + if (_tree != null) + { + foreach (var (_, entity) in _tree) + { + entity.Dispose(); + } + + scene.EntitySortedDictionaryPool.Return(_tree); + _tree = null; + } + + if (_multi != null) + { + foreach (var (_, entity) in _multi) + { + entity.Dispose(); + } + + scene.EntitySortedDictionaryPool.Return(_multi); + _multi = null; + } +#if FANTASY_NET + if (_treeDb != null) + { + foreach (var entity in _treeDb) + { + entity.Dispose(); + } + + scene.EntityListPool.Return(_treeDb); + _treeDb = null; + } + + if (_multiDb != null) + { + foreach (var entity in _multiDb) + { + entity.Dispose(); + } + + scene.EntityListPool.Return(_multiDb); + _multiDb = null; + } +#endif + scene.EntityComponent.Destroy(this); + + if (Parent != null && Parent != this && !Parent.IsDisposed) + { + Parent.RemoveComponent(this, false); + Parent = null; + } + + Id = 0; + Scene = null; + Parent = null; + scene.RemoveEntity(runTimeId); + + if (IsPool()) + { + scene.EntityPool.Return(Type, this); + } + + Type = null; + } + + #endregion + + #region Pool + + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + + #endregion + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Entity.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Entity.cs.meta new file mode 100644 index 00000000..4b46a48b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Entity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a47c9eec9972439e88417f2f4b18482 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityPool.cs new file mode 100644 index 00000000..9a6441c0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityPool.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using Fantasy.Pool; + +#pragma warning disable CS8714 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint. + +namespace Fantasy.Entitas +{ + internal sealed class EntityPool : PoolCore + { + public EntityPool() : base(4096) { } + } + + internal sealed class EntityList : List, IPool where T : Entity + { + private bool _isPool; + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + internal sealed class EntityListPool : PoolCore> where T : Entity + { + public EntityListPool() : base(4096) { } + } + + internal sealed class EntitySortedDictionary : SortedDictionary, IPool where TN : Entity + { + private bool _isPool; + /// + /// 获取一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public bool IsPool() + { + return _isPool; + } + + /// + /// 设置一个值,该值指示当前实例是否为对象池中的实例。 + /// + /// + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } + + internal sealed class EntitySortedDictionaryPool : PoolCore> where TN : Entity + { + public EntitySortedDictionaryPool() : base(4096) { } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityPool.cs.meta new file mode 100644 index 00000000..6bc9fac0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f30a1dcea6418429889f3e2216a883c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityReference.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityReference.cs new file mode 100644 index 00000000..dd1a3fd4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityReference.cs @@ -0,0 +1,59 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.Entitas +{ + /// + /// 实体引用检查组件 + /// + /// + public struct EntityReference where T : Entity + { + private T _entity; + private readonly long _runTimeId; + + private EntityReference(T t) + { + if (t == null) + { + _entity = null; + _runTimeId = 0; + return; + } + + _entity = t; + _runTimeId = t.RuntimeId; + } + + /// + /// 将一个实体转换为EntityReference + /// + /// 实体泛型类型 + /// 返回一个EntityReference + public static implicit operator EntityReference(T t) + { + return new EntityReference(t); + } + + /// + /// 将一个EntityReference转换为实体 + /// + /// 实体泛型类型 + /// 当实体已经被销毁过会返回null + public static implicit operator T(EntityReference v) + { + if (v._entity == null) + { + return null; + } + + if (v._entity.RuntimeId != v._runTimeId) + { + v._entity = null; + } + + return v._entity; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityReference.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityReference.cs.meta new file mode 100644 index 00000000..8e9553ff --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/EntityReference.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aba2430182a244c3393abe66830172b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface.meta new file mode 100644 index 00000000..291e641a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9b2fb651801ec40d1a0565114e0059d6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported.meta new file mode 100644 index 00000000..b20488c2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9255f085833224805bf13e026b755fd2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs new file mode 100644 index 00000000..a25b2b7a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs @@ -0,0 +1,19 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Entitas.Interface +{ + /// + /// Entity保存到数据库的时候会根据子组件设置分离存储特性分表存储在不同的集合表中 + /// + public interface ISingleCollectionRoot { } + public static class SingleCollectionRootChecker where T : Entity + { + public static bool IsSupported { get; } + + static SingleCollectionRootChecker() + { + IsSupported = typeof(ISingleCollectionRoot).IsAssignableFrom(typeof(T)); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta new file mode 100644 index 00000000..94cbb13b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISingleCollectionRoot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57298dd8265554d6087d79ef5a6e89cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs new file mode 100644 index 00000000..ad9013bf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs @@ -0,0 +1,21 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Entitas.Interface +{ + /// + /// Entity支持数据库 + /// + // ReSharper disable once InconsistentNaming + public interface ISupportedDataBase { } + + public static class SupportedDataBaseChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedDataBaseChecker() + { + IsSupported = typeof(ISupportedDataBase).IsAssignableFrom(typeof(T)); + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta new file mode 100644 index 00000000..4b72ec6b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedDataBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae64989e8b146443e99c66290b20a3c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs new file mode 100644 index 00000000..ee6aeb7c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs @@ -0,0 +1,20 @@ +using System; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Entitas.Interface +{ + /// + /// 支持再一个组件里添加多个同类型组件 + /// + public interface ISupportedMultiEntity : IDisposable { } + + public static class SupportedMultiEntityChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedMultiEntityChecker() + { + IsSupported = typeof(ISupportedMultiEntity).IsAssignableFrom(typeof(T)); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta new file mode 100644 index 00000000..4096fe8e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedMultiEntity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36105e7ed5c974fdabf37eead97ef95c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs new file mode 100644 index 00000000..302e6978 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs @@ -0,0 +1,47 @@ +using System; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Entitas.Interface +{ + // Entity是单一集合、保存到数据库的时候不会跟随父组件保存在一个集合里、会单独保存在一个集合里 + // 需要配合SingleCollectionAttribute一起使用、如在Entity类头部定义SingleCollectionAttribute(typeOf(Unit)) + // SingleCollectionAttribute用来定义这个Entity是属于哪个Entity的子集 + /// + /// 定义实体支持单一集合存储的接口。当实体需要单独存储在一个集合中,并且在保存到数据库时不会与父组件一起保存在同一个集合中时,应实现此接口。 + /// + public interface ISupportedSingleCollection { } + public static class SupportedSingleCollectionChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedSingleCollectionChecker() + { + IsSupported = typeof(ISupportedSingleCollection).IsAssignableFrom(typeof(T)); + } + } + /// + /// 表示用于指定实体的单一集合存储属性。此属性用于配合 接口使用, + /// 用于定义实体属于哪个父实体的子集合,以及在数据库中使用的集合名称。 + /// + [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] + public class SingleCollectionAttribute : Attribute + { + /// + /// 获取父实体的类型,指示此实体是属于哪个父实体的子集合。 + /// + public readonly Type RootType; + /// + /// 获取在数据库中使用的集合名称。 + /// + public readonly string CollectionName; + /// + /// 初始化 类的新实例,指定父实体类型和集合名称。 + /// + /// 父实体的类型。 + /// 在数据库中使用的集合名称。 + public SingleCollectionAttribute(Type rootType, string collectionName) + { + RootType = rootType; + CollectionName = collectionName; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta new file mode 100644 index 00000000..dc89d3b1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedSingleCollection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afd453d04ac254206a9bb83664a888a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs new file mode 100644 index 00000000..a3ae4a97 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs @@ -0,0 +1,19 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Entitas.Interface +{ + /// + /// Entity支持传送 + /// + public interface ISupportedTransfer { } + public static class SupportedTransferChecker where T : Entity + { + public static bool IsSupported { get; } + + static SupportedTransferChecker() + { + IsSupported = typeof(ISupportedTransfer).IsAssignableFrom(typeof(T)); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta new file mode 100644 index 00000000..8f1493c9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/Supported/ISupportedTransfer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a127a7c6e345a42e3860b804457f0fe5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System.meta new file mode 100644 index 00000000..01495d44 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 275ef1a555d6f41cbb322011303dd57c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IAwakeSystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IAwakeSystem.cs new file mode 100644 index 00000000..f651701d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IAwakeSystem.cs @@ -0,0 +1,32 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + internal interface IAwakeSystem : IEntitiesSystem { } + /// + /// 实体的Awake事件的抽象接口 + /// + /// 实体的泛型类型 + public abstract class AwakeSystem : IAwakeSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Awake(T self); + /// + /// 框架内部调用的触发Awake的方法。 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Awake((T) self); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta new file mode 100644 index 00000000..782be94b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IAwakeSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fe2caf80007df454bb76729547780d28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDeserializeSystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDeserializeSystem.cs new file mode 100644 index 00000000..9c38ab6b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDeserializeSystem.cs @@ -0,0 +1,32 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + internal interface IDeserializeSystem : IEntitiesSystem { } + /// + /// 实体的反序列化事件的抽象接口 + /// + /// 实体的泛型数据 + public abstract class DeserializeSystem : IDeserializeSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Deserialize(T self); + /// + /// 框架内部调用的触发Deserialize的方法 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Deserialize((T) self); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta new file mode 100644 index 00000000..b2b90be2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDeserializeSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f9d2fff74aed249e8aa0acbb122614c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDestroySystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDestroySystem.cs new file mode 100644 index 00000000..531ebbe0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDestroySystem.cs @@ -0,0 +1,32 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + internal interface IDestroySystem : IEntitiesSystem { } + /// + /// 实体销毁事件的抽象接口 + /// + /// + public abstract class DestroySystem : IDestroySystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Destroy(T self); + /// + /// 框架内部调用的触发Destroy的方法 + /// + /// + public void Invoke(Entity self) + { + Destroy((T) self); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDestroySystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDestroySystem.cs.meta new file mode 100644 index 00000000..f46b2c4b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IDestroySystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 899a57e15b99948c7bcaef5b76cae97c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IEntitiesSystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IEntitiesSystem.cs new file mode 100644 index 00000000..555d21a8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IEntitiesSystem.cs @@ -0,0 +1,22 @@ +using System; +using Fantasy.Async; + +namespace Fantasy.Entitas.Interface +{ + /// + /// ECS事件系统的核心接口,任何事件都是要继承这个接口 + /// + public interface IEntitiesSystem + { + /// + /// 实体的类型 + /// + /// + Type EntitiesType(); + /// + /// 框架内部调用的触发事件方法 + /// + /// + void Invoke(Entity entity); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta new file mode 100644 index 00000000..d5370f10 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IEntitiesSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 287ae5e33ccda4c28946371bcad4755b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IFrameUpdateSystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IFrameUpdateSystem.cs new file mode 100644 index 00000000..c50061b1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IFrameUpdateSystem.cs @@ -0,0 +1,31 @@ +using System; + +namespace Fantasy.Entitas.Interface +{ + internal interface IFrameUpdateSystem : IEntitiesSystem { } + /// + /// 帧更新时间的抽象接口 + /// + /// + public abstract class FrameUpdateSystem : IFrameUpdateSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void FrameUpdate(T self); + /// + /// 框架内部调用的触发FrameUpdate的方法 + /// + /// + public void Invoke(Entity self) + { + FrameUpdate((T) self); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IFrameUpdateSystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IFrameUpdateSystem.cs.meta new file mode 100644 index 00000000..866ab9ae --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IFrameUpdateSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b785fffadcd8c4461b1f1fcf397728b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IUpdateSystem.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IUpdateSystem.cs new file mode 100644 index 00000000..4b34ac8f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IUpdateSystem.cs @@ -0,0 +1,31 @@ +using System; + +namespace Fantasy.Entitas.Interface +{ + internal interface IUpdateSystem : IEntitiesSystem { } + /// + /// Update事件的抽象接口 + /// + /// + public abstract class UpdateSystem : IUpdateSystem where T : Entity + { + /// + /// 实体的类型 + /// + /// + public Type EntitiesType() => typeof(T); + /// + /// 事件的抽象方法,需要自己实现这个方法 + /// + /// 触发事件的实体实例 + protected abstract void Update(T self); + /// + /// 框架内部调用的触发Update的方法 + /// + /// 触发事件的实体实例 + public void Invoke(Entity self) + { + Update((T) self); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta new file mode 100644 index 00000000..a78de3db --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Entitas/Interface/System/IUpdateSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a40db65b7285747ffad3a0346966406c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper.meta new file mode 100644 index 00000000..c54fa758 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cc72684821a1e4f3082e9b1b1c7cdba2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/ByteHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/ByteHelper.cs new file mode 100644 index 00000000..e3e46cd0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/ByteHelper.cs @@ -0,0 +1,371 @@ +using System; +using System.Buffers; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; + +namespace Fantasy.Helper +{ + /// + /// 提供字节操作辅助方法的静态类。 + /// + public static class ByteHelper + { + private static readonly string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" }; + + /// + /// 从指定的文件流中读取一个 64 位整数。 + /// + public static long ReadInt64(FileStream stream) + { + var buffer = new byte[8]; + stream.Read(buffer, 0, 8); + return BitConverter.ToInt64(buffer, 0); + } + + /// + /// 从指定的文件流中读取一个 32 位整数。 + /// + public static int ReadInt32(FileStream stream) + { + var buffer = new byte[4]; + stream.Read(buffer, 0, 4); + return BitConverter.ToInt32(buffer, 0); + } + + /// + /// 从指定的内存流中读取一个 64 位整数。 + /// + public static long ReadInt64(MemoryStream stream) + { + var buffer = new byte[8]; + stream.Read(buffer, 0, 8); + return BitConverter.ToInt64(buffer, 0); + } + + /// + /// 从指定的内存流中读取一个 32 位整数。 + /// + public static int ReadInt32(MemoryStream stream) + { + var buffer = new byte[4]; + stream.Read(buffer, 0, 4); + return BitConverter.ToInt32(buffer, 0); + } + + /// + /// 将字节转换为十六进制字符串表示。 + /// + public static string ToHex(this byte b) + { + return b.ToString("X2"); + } + + /// + /// 将字节数组转换为十六进制字符串表示。 + /// + public static string ToHex(this byte[] bytes) + { + var stringBuilder = new StringBuilder(); + foreach (var b in bytes) + { + stringBuilder.Append(b.ToString("X2")); + } + + return stringBuilder.ToString(); + } + + /// + /// 将字节数组按指定格式转换为十六进制字符串表示。 + /// + public static string ToHex(this byte[] bytes, string format) + { + var stringBuilder = new StringBuilder(); + foreach (var b in bytes) + { + stringBuilder.Append(b.ToString(format)); + } + + return stringBuilder.ToString(); + } + + /// + /// 将字节数组的指定范围按十六进制格式转换为字符串表示。 + /// + public static string ToHex(this byte[] bytes, int offset, int count) + { + var stringBuilder = new StringBuilder(); + for (var i = offset; i < offset + count; ++i) + { + stringBuilder.Append(bytes[i].ToString("X2")); + } + + return stringBuilder.ToString(); + } + + /// + /// 将字节数组转换为默认编码的字符串表示。 + /// + public static string ToStr(this byte[] bytes) + { + return Encoding.Default.GetString(bytes); + } + + /// + /// 将字节数组的指定范围按默认编码转换为字符串表示。 + /// + public static string ToStr(this byte[] bytes, int index, int count) + { + return Encoding.Default.GetString(bytes, index, count); + } + + /// + /// 将字节数组转换为 UTF-8 编码的字符串表示。 + /// + public static string Utf8ToStr(this byte[] bytes) + { + return Encoding.UTF8.GetString(bytes); + } + + /// + /// 将字节数组的指定范围按 UTF-8 编码转换为字符串表示。 + /// + public static string Utf8ToStr(this byte[] bytes, int index, int count) + { + return Encoding.UTF8.GetString(bytes, index, count); + } + + /// + /// 将无符号整数写入字节数组的指定偏移位置。 + /// + public static void WriteTo(this byte[] bytes, int offset, uint num) + { + bytes[offset] = (byte)(num & 0xff); + bytes[offset + 1] = (byte)((num & 0xff00) >> 8); + bytes[offset + 2] = (byte)((num & 0xff0000) >> 16); + bytes[offset + 3] = (byte)((num & 0xff000000) >> 24); + } + + /// + /// 将有符号整数写入字节数组的指定偏移位置。 + /// + public static void WriteTo(this byte[] bytes, int offset, int num) + { + bytes[offset] = (byte)(num & 0xff); + bytes[offset + 1] = (byte)((num & 0xff00) >> 8); + bytes[offset + 2] = (byte)((num & 0xff0000) >> 16); + bytes[offset + 3] = (byte)((num & 0xff000000) >> 24); + } + + /// + /// 将字节写入字节数组的指定偏移位置。 + /// + public static void WriteTo(this byte[] bytes, int offset, byte num) + { + bytes[offset] = num; + } + + /// + /// 将有符号短整数写入字节数组的指定偏移位置。 + /// + public static void WriteTo(this byte[] bytes, int offset, short num) + { + bytes[offset] = (byte)(num & 0xff); + bytes[offset + 1] = (byte)((num & 0xff00) >> 8); + } + + /// + /// 将无符号短整数写入字节数组的指定偏移位置。 + /// + public static void WriteTo(this byte[] bytes, int offset, ushort num) + { + bytes[offset] = (byte)(num & 0xff); + bytes[offset + 1] = (byte)((num & 0xff00) >> 8); + } + + /// + /// 将字节数转换为可读的速度表示。 + /// + /// 字节数 + /// 可读的速度表示 + public static string ToReadableSpeed(this long byteCount) + { + var i = 0; + double dblSByte = byteCount; + if (byteCount <= 1024) + { + return $"{dblSByte:0.##}{Suffix[i]}"; + } + + for (i = 0; byteCount / 1024 > 0; i++, byteCount /= 1024) + { + dblSByte = byteCount / 1024.0; + } + + return $"{dblSByte:0.##}{Suffix[i]}"; + } + + /// + /// 将字节数转换为可读的速度表示。 + /// + /// 字节数 + /// 可读的速度表示 + public static string ToReadableSpeed(this ulong byteCount) + { + var i = 0; + double dblSByte = byteCount; + + if (byteCount <= 1024) + { + return $"{dblSByte:0.##}{Suffix[i]}"; + } + + for (i = 0; byteCount / 1024 > 0; i++, byteCount /= 1024) + { + dblSByte = byteCount / 1024.0; + } + + return $"{dblSByte:0.##}{Suffix[i]}"; + } + + /// + /// 合并两个字节数组。 + /// + /// 第一个字节数组 + /// 第二个字节数组 + /// 合并后的字节数组 + public static byte[] MergeBytes(byte[] bytes, byte[] otherBytes) + { + var result = new byte[bytes.Length + otherBytes.Length]; + bytes.CopyTo(result, 0); + otherBytes.CopyTo(result, bytes.Length); + return result; + } + + /// + /// 根据int值获取字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetBytes(this int value, byte[] buffer) + { + if (buffer.Length < 4) + { + throw new ArgumentException("Buffer too small."); + } + +#if FANTASY_NET || FANTASY_CONSOLE + MemoryMarshal.Write(buffer.AsSpan(), in value); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(buffer.AsSpan(), ref value); +#endif + } + + /// + /// 根据int值获取字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteBytes(this MemoryStream memoryStream, int value) + { + using var memoryOwner = MemoryPool.Shared.Rent(4); + var memorySpan = memoryOwner.Memory.Span; +#if FANTASY_NET + MemoryMarshal.Write(memorySpan, in value); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(memorySpan, ref value); +#endif + memoryStream.Write(memorySpan); + } + + /// + /// 根据uint值获取字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetBytes(ref this uint value, byte[] buffer) + { + if (buffer.Length < 4) + { + throw new ArgumentException("Buffer too small."); + } + +#if FANTASY_NET + MemoryMarshal.Write(buffer.AsSpan(), in value); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(buffer.AsSpan(), ref value); +#endif + } + + /// + /// 根据uint值获取字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteBytes(this MemoryStream memoryStream, uint value) + { + using var memoryOwner = MemoryPool.Shared.Rent(4); + var memorySpan = memoryOwner.Memory.Span; +#if FANTASY_NET + MemoryMarshal.Write(memorySpan, in value); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(memorySpan, ref value); +#endif + memoryStream.Write(memorySpan); + } + + /// + /// 根据int值获取字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void GetBytes(this long value, byte[] buffer) + { + if (buffer.Length < 8) + { + throw new ArgumentException("Buffer too small."); + } +#if FANTASY_NET + MemoryMarshal.Write(buffer.AsSpan(), in value); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(buffer.AsSpan(), ref value); +#endif + } + + /// + /// 根据uint值获取字节数组。 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteBytes(this MemoryStream memoryStream, long value) + { + using var memoryOwner = MemoryPool.Shared.Rent(8); + var memorySpan = memoryOwner.Memory.Span; +#if FANTASY_NET + MemoryMarshal.Write(memorySpan, in value); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(memorySpan, ref value); +#endif + memoryStream.Write(memorySpan); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/ByteHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/ByteHelper.cs.meta new file mode 100644 index 00000000..53c89988 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/ByteHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d992f9fd88d64d9085ab2945d98c3d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/EncryptHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/EncryptHelper.cs new file mode 100644 index 00000000..be950bc6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/EncryptHelper.cs @@ -0,0 +1,63 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Fantasy.Helper +{ + /// + /// 提供计算 MD5 散列值的辅助方法。 + /// + public static partial class EncryptHelper + { + private static readonly SHA256 Sha256Hash = SHA256.Create(); + + /// + /// 计算指定字节数组的Sha256。 + /// + /// + /// + public static byte[] ComputeSha256Hash(byte[] bytes) + { +#if FANTASY_UNITY + using var sha256Hash = SHA256.Create(); + return sha256Hash.ComputeHash(bytes); +#else + return SHA256.HashData(bytes); +#endif + } + + /// + /// 计算指定文件的 MD5 散列值。 + /// + /// 要计算散列值的文件路径。 + /// 表示文件的 MD5 散列值的字符串。 + public static string FileMD5(string filePath) + { + using var file = new FileStream(filePath, FileMode.Open); + return FileMD5(file); + } + + /// + /// 计算给定文件流的 MD5 散列值。 + /// + /// 要计算散列值的文件流。 + /// 表示文件流的 MD5 散列值的字符串。 + public static string FileMD5(FileStream fileStream) + { + var md5 = MD5.Create(); + return md5.ComputeHash(fileStream).ToHex("x2"); + } + + /// + /// 计算给定字节数组的 MD5 散列值。 + /// + /// 要计算散列值的字节数组。 + /// 表示字节数组的 MD5 散列值的字符串。 + public static string BytesMD5(byte[] bytes) + { + var md5 = MD5.Create(); + bytes = md5.ComputeHash(bytes); + return bytes.ToHex("x2"); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/EncryptHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/EncryptHelper.cs.meta new file mode 100644 index 00000000..5dc15c41 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/EncryptHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c09f5dc7247c4396b293e9c91b42361 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/FileHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/FileHelper.cs new file mode 100644 index 00000000..058db829 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/FileHelper.cs @@ -0,0 +1,175 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace Fantasy.Helper +{ + /// + /// 文件操作助手类,提供了各种文件操作方法。 + /// + public static partial class FileHelper + { + /// + /// 获取相对路径的完整路径。 + /// + /// 相对路径。 + /// 完整路径。 + public static string GetFullPath(string relativePath) + { + return Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), relativePath)); + } + + /// + /// 获取相对路径的的文本信息。 + /// + /// + /// + public static async Task GetTextByRelativePath(string relativePath) + { + var fullPath = GetFullPath(relativePath); + return await File.ReadAllTextAsync(fullPath, Encoding.UTF8); + } + + /// + /// 获取绝对路径的的文本信息。 + /// + /// + /// + public static async Task GetText(string fullPath) + { + return await File.ReadAllTextAsync(fullPath, Encoding.UTF8); + } + + /// + /// 根据文件夹路径创建文件夹,如果文件夹不存在会自动创建文件夹。 + /// + /// + public static void CreateDirectory(string directoryPath) + { + if (directoryPath.LastIndexOf('/') != directoryPath.Length - 1) + { + directoryPath += "/"; + } + + var directoriesByFilePath = GetDirectoriesByFilePath(directoryPath); + + foreach (var dir in directoriesByFilePath) + { + if (Directory.Exists(dir)) + { + continue; + } + + Directory.CreateDirectory(dir); + } + } + + /// + /// 将文件复制到目标路径,如果目标目录不存在会自动创建目录。 + /// + /// 源文件路径。 + /// 目标文件路径。 + /// 是否覆盖已存在的目标文件。 + public static void Copy(string sourceFile, string destinationFile, bool overwrite) + { + CreateDirectory(destinationFile); + File.Copy(sourceFile, destinationFile, overwrite); + } + + /// + /// 获取文件路径内的所有文件夹路径。 + /// + /// 文件路径。 + /// 文件夹路径列表。 + public static IEnumerable GetDirectoriesByFilePath(string filePath) + { + var dir = ""; + var fileDirectories = filePath.Split('/'); + + for (var i = 0; i < fileDirectories.Length - 1; i++) + { + dir = $"{dir}{fileDirectories[i]}/"; + yield return dir; + } + + if (fileDirectories.Length == 1) + { + yield return filePath; + } + } + + /// + /// 将文件夹内的所有内容复制到目标位置。 + /// + /// 源文件夹路径。 + /// 目标文件夹路径。 + /// 是否覆盖已存在的文件。 + public static void CopyDirectory(string sourceDirectory, string destinationDirectory, bool overwrite) + { + // 创建目标文件夹 + + if (!Directory.Exists(destinationDirectory)) + { + Directory.CreateDirectory(destinationDirectory); + } + + // 获取当前文件夹中的所有文件 + + var files = Directory.GetFiles(sourceDirectory); + + // 拷贝文件到目标文件夹 + + foreach (var file in files) + { + var fileName = Path.GetFileName(file); + var destinationPath = Path.Combine(destinationDirectory, fileName); + File.Copy(file, destinationPath, overwrite); + } + + // 获取源文件夹中的所有子文件夹 + + var directories = Directory.GetDirectories(sourceDirectory); + + // 递归方式拷贝文件夹 + + foreach (var directory in directories) + { + var directoryName = Path.GetFileName(directory); + var destinationPath = Path.Combine(destinationDirectory, directoryName); + CopyDirectory(directory, destinationPath, overwrite); + } + } + + /// + /// 获取目录下的所有文件 + /// + /// 文件夹路径。 + /// 需要查找的文件通配符 + /// 查找的类型 + /// + public static string[] GetDirectoryFile(string folderPath, string searchPattern, SearchOption searchOption) + { + return Directory.GetFiles(folderPath, searchPattern, searchOption); + } + + /// + /// 清空文件夹内的所有文件。 + /// + /// 文件夹路径。 + public static void ClearDirectoryFile(string folderPath) + { + if (!Directory.Exists(folderPath)) + { + return; + } + + var files = Directory.GetFiles(folderPath); + + foreach (var file in files) + { + File.Delete(file); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/FileHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/FileHelper.cs.meta new file mode 100644 index 00000000..c341e6b3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/FileHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb7aa7f0698f4409da7f0cdb32e8d8ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HashCodeHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HashCodeHelper.cs new file mode 100644 index 00000000..42be4e4d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HashCodeHelper.cs @@ -0,0 +1,129 @@ +using System.Security.Cryptography; +using System.Text; +// ReSharper disable InconsistentNaming + +namespace Fantasy.Helper +{ + /// + /// HashCode算法帮助类 + /// + public static partial class HashCodeHelper + { + private static readonly SHA256 Sha256Hash = SHA256.Create(); + + /// + /// 使用bkdr算法生成一个long的值 + /// + /// + /// + public static unsafe long GetBKDRHashCode(string str) + { + ulong hash = 0; + // 如果要修改这个种子、建议选择一个质数来做种子 + const uint seed = 13131; // 31 131 1313 13131 131313 etc.. + fixed (char* p = str) + { + for (var i = 0; i < str.Length; i++) + { + var c = p[i]; + var high = (byte)(c >> 8); + var low = (byte)(c & byte.MaxValue); + hash = hash * seed + high; + hash = hash * seed + low; + } + } + return (long)hash; + } + + /// + /// 使用MurmurHash3算法生成一个uint的值 + /// + /// + /// + public static unsafe uint MurmurHash3(string str) + { + const uint seed = 0xc58f1a7b; + uint hash = seed; + uint c1 = 0xcc9e2d51; + uint c2 = 0x1b873593; + + fixed (char* p = str) + { + var current = p; + + for (var i = 0; i < str.Length; i++) + { + var k1 = (uint)(*current); + k1 *= c1; + k1 = (k1 << 15) | (k1 >> (32 - 15)); + k1 *= c2; + + hash ^= k1; + hash = (hash << 13) | (hash >> (32 - 13)); + hash = hash * 5 + 0xe6546b64; + + current++; + } + } + + hash ^= (uint)str.Length; + hash ^= hash >> 16; + hash *= 0x85ebca6b; + hash ^= hash >> 13; + hash *= 0xc2b2ae35; + hash ^= hash >> 16; + return hash; + } + + /// + /// 使用MurmurHash3算法生成一个long的值 + /// + /// + /// + public static unsafe long ComputeHash64(string str) + { + const ulong seed = 0xc58f1a7bc58f1a7bUL; // 64-bit seed + var hash = seed; + var c1 = 0x87c37b91114253d5UL; + var c2 = 0x4cf5ad432745937fUL; + + fixed (char* p = str) + { + var current = p; + + for (var i = 0; i < str.Length; i++) + { + var k1 = (ulong)(*current); + k1 *= c1; + k1 = (k1 << 31) | (k1 >> (64 - 31)); + k1 *= c2; + + hash ^= k1; + hash = (hash << 27) | (hash >> (64 - 27)); + hash = hash * 5 + 0x52dce729; + + current++; + } + } + + hash ^= (ulong)str.Length; + hash ^= hash >> 33; + hash *= 0xff51afd7ed558ccdUL; + hash ^= hash >> 33; + hash *= 0xc4ceb9fe1a85ec53UL; + hash ^= hash >> 33; + return (long)hash; + } + + /// + /// 根据字符串计算一个Hash值 + /// + /// + /// + public static int ComputeSha256HashAsInt(string rawData) + { + var bytes = Sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData)); + return (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HashCodeHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HashCodeHelper.cs.meta new file mode 100644 index 00000000..406fe87b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HashCodeHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6ec2f7d0b1e3d4605bc7224099e156a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient.meta new file mode 100644 index 00000000..fe15834d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 724626f87e31e4ac4a3098336100c034 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientHelper.cs new file mode 100644 index 00000000..6ecb62a1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientHelper.cs @@ -0,0 +1,145 @@ +#if !FANTASY_WEBGL +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Pool; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Http +{ + /// + /// HTTP帮助类 + /// + public static partial class HttpClientHelper + { + private static readonly HttpClient Client = new HttpClient(new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true + }); + + /// + /// 用Post方式请求string数据 + /// + /// + /// + /// + /// + public static async UniTask CallNotDeserializeByPost(string url, HttpContent content) + { + var response = await Client.PostAsync(url, content); + + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"Unable to connect to server url {(object)url} HttpStatusCode:{(object)response.StatusCode}"); + } + + return await response.Content.ReadAsStringAsync(); + } + + /// + /// 用Get方式请求string数据 + /// + /// + /// + /// + public static async UniTask CallNotDeserializeByGet(string url) + { + var response = await Client.GetAsync(url); + + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"Unable to connect to server url {(object)url} HttpStatusCode:{(object)response.StatusCode}"); + } + + return await response.Content.ReadAsStringAsync(); + } + + /// + /// 用Post方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + /// + public static async UniTask CallByPost(string url, HttpContent content) + { + return await Deserialize(url, await Client.PostAsync(url, content)); + } + + /// + /// 用Post方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + /// + public static async UniTask CallByPost(string url, HttpMethod method) + { + return await Deserialize(url, await Client.SendAsync(new HttpRequestMessage(method, url))); + } + + /// + /// 用Get方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + public static async UniTask CallByGet(string url) + { + return await Deserialize(url, await Client.GetAsync(url)); + } + + /// + /// 用Post方式请求JSON数据,并自动把JSON转换为对象。 + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static async UniTask Call(string url, int id, AuthenticationHeaderValue authentication, string method, params object[] @params) where TRequest : class, IJsonRpcRequest, new() + { + var request = Pool.Rent(); + using var httpClientPool = HttpClientPool.Create(); + var client = httpClientPool.Client; + client.DefaultRequestHeaders.Authorization = authentication; + + try + { + request.Init(method, id, @params); + var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json"); + var response = await Deserialize(url, await client.PostAsync(url, content)); + return response; + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + Pool.Return(request); + } + + return default; + } + + private static async UniTask Deserialize(string url, HttpResponseMessage response) + { + if (response.StatusCode != HttpStatusCode.OK) + { + throw new Exception($"Unable to connect to server url {(object)url} HttpStatusCode:{(object)response.StatusCode}"); + } + + return (await response.Content.ReadAsStringAsync()).Deserialize(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientHelper.cs.meta new file mode 100644 index 00000000..70e3bd5e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f8005f3a1a1945a2929442f82832e765 +timeCreated: 1726023741 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientPool.cs new file mode 100644 index 00000000..de421ff9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientPool.cs @@ -0,0 +1,44 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Net.Http; +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Http +{ + internal class HttpClientPool : IDisposable + { + private bool IsDispose { get; set; } + public HttpClient Client { get; private set; } + private static readonly Queue Pools = new Queue(); + private static readonly HttpClientHandler ClientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true + }; + + public static HttpClientPool Create() + { + if (Pools.TryDequeue(out var httpClientPool)) + { + httpClientPool.IsDispose = false; + return httpClientPool; + } + + httpClientPool = new HttpClientPool(); + httpClientPool.Client = new HttpClient(ClientHandler); + return httpClientPool; + } + + public void Dispose() + { + if (IsDispose) + { + return; + } + + IsDispose = true; + Pools.Enqueue(this); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientPool.cs.meta new file mode 100644 index 00000000..a1ac3bfa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/HttpClientPool.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a78c441357d244d5ba490a13c89e1c50 +timeCreated: 1726023895 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/IJsonRpcRequest.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/IJsonRpcRequest.cs new file mode 100644 index 00000000..ae756c5b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/IJsonRpcRequest.cs @@ -0,0 +1,20 @@ +using Fantasy.Pool; + +#if !FANTASY_WEBGL +namespace Fantasy.Http +{ + /// + /// 一个JsonRPC的接口 + /// + public interface IJsonRpcRequest : IPool + { + /// + /// 用于初始化这个Json对象 + /// + /// + /// + /// + void Init(string method, int id, params object[] @params); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta new file mode 100644 index 00000000..9e01783d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/HttpClient/IJsonRpcRequest.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 72a03580c619417b9f8f92d99938e371 +timeCreated: 1726023900 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/JsonHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/JsonHelper.cs new file mode 100644 index 00000000..2b10fab7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/JsonHelper.cs @@ -0,0 +1,57 @@ +using System; +using Newtonsoft.Json; +#pragma warning disable CS8603 + +namespace Fantasy.Helper +{ + /// + /// 提供操作 JSON 数据的辅助方法。 + /// + public static partial class JsonHelper + { + /// + /// 将对象序列化为 JSON 字符串。 + /// + /// 要序列化的对象类型。 + /// 要序列化的对象。 + /// 表示序列化对象的 JSON 字符串。 + public static string ToJson(this T t) + { + return JsonConvert.SerializeObject(t); + } + + /// + /// 反序列化 JSON 字符串为指定类型的对象。 + /// + /// 要反序列化的 JSON 字符串。 + /// 目标对象的类型。 + /// 是否使用反射进行反序列化(默认为 true)。 + /// 反序列化后的对象。 + public static object Deserialize(this string json, Type type, bool reflection = true) + { + return JsonConvert.DeserializeObject(json, type); + } + + /// + /// 反序列化 JSON 字符串为指定类型的对象。 + /// + /// 目标对象的类型。 + /// 要反序列化的 JSON 字符串。 + /// 反序列化后的对象。 + public static T Deserialize(this string json) + { + return JsonConvert.DeserializeObject(json); + } + + /// + /// 克隆对象,通过将对象序列化为 JSON,然后再进行反序列化。 + /// + /// 要克隆的对象类型。 + /// 要克隆的对象。 + /// 克隆后的对象。 + public static T Clone(T t) + { + return t.ToJson().Deserialize(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/JsonHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/JsonHelper.cs.meta new file mode 100644 index 00000000..0459592b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/JsonHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f25483965eb6459583e1d328adc8f05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/NetworkHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/NetworkHelper.cs new file mode 100644 index 00000000..6a35a613 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/NetworkHelper.cs @@ -0,0 +1,443 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#pragma warning disable CS8603 // Possible null reference return. + +// ReSharper disable InconsistentNaming + +namespace Fantasy.Helper +{ + /// + /// 提供网络操作相关的帮助方法。 + /// + public static partial class NetworkHelper + { + /// + /// 根据字符串获取一个IPEndPoint + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IPEndPoint GetIPEndPoint(string address) + { + try + { + var addressSplit = address.Split(':'); + if (addressSplit.Length != 2) + { + throw new FormatException("Invalid format"); + } + + var ipString = addressSplit[0]; + var portString = addressSplit[1]; + + if (!IPAddress.TryParse(ipString, out var ipAddress)) + { + throw new FormatException("Invalid IP address"); + } + + if (!int.TryParse(portString, out var port) || port < 0 || port > 65535) + { + throw new FormatException("Invalid port number"); + } + + return new IPEndPoint(ipAddress, port); + } + catch (Exception e) + { + Log.Error($"Error parsing IP and Port:{e.Message}"); + return null; + } + } + + /// + /// 克隆一个IPEndPoint + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IPEndPoint Clone(this EndPoint endPoint) + { + var ip = (IPEndPoint)endPoint; + return new IPEndPoint(ip.Address, ip.Port); + } + + /// + /// 比较两个IPEndPoint是否相等 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IPEndPointEquals(this EndPoint endPoint, IPEndPoint ipEndPoint) + { + var ip = (IPEndPoint)endPoint; + return ip.Address.Equals(ipEndPoint.Address) && ip.Port == ipEndPoint.Port; + } + + /// + /// 比较两个IPEndPoint是否相等 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IPEndPointEquals(this IPEndPoint endPoint, IPEndPoint ipEndPoint) + { + return endPoint.Address.Equals(ipEndPoint.Address) && endPoint.Port == ipEndPoint.Port; + } + +#if !FANTASY_WEBGL + /// + /// 将SocketAddress写入到Byte[]中 + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void SocketAddressToByte(this SocketAddress socketAddress, byte[] buffer, int offset) + { + if (socketAddress == null) + { + throw new ArgumentNullException(nameof(socketAddress), "The SocketAddress cannot be null."); + } + + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer), "The buffer cannot be null."); + } + + if (buffer.Length < socketAddress.Size + offset + 8) + { + throw new ArgumentException("The buffer length is insufficient. It must be at least the size of the SocketAddress plus 8 bytes.", nameof(buffer)); + } + + fixed (byte* pBuffer = buffer) + { + var pOffsetBuffer = pBuffer + offset; + var addressFamilyValue = (int)socketAddress.Family; + var socketAddressSizeValue = socketAddress.Size; + Buffer.MemoryCopy(&addressFamilyValue, pOffsetBuffer, buffer.Length - offset, sizeof(int)); + Buffer.MemoryCopy(&socketAddressSizeValue, pOffsetBuffer + 4, buffer.Length - offset -4, sizeof(int)); + for (var i = 0; i < socketAddress.Size - 2; i++) + { + pOffsetBuffer[8 + i] = socketAddress[i + 2]; + } + } + } + + /// + /// 将byre[]转换为SocketAddress + /// + /// + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int ByteToSocketAddress(byte[] buffer, int offset, out SocketAddress socketAddress) + { + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer), "The buffer cannot be null."); + } + + if (buffer.Length < 8) + { + throw new ArgumentException("Buffer length is insufficient. It must be at least 8 bytes.", nameof(buffer)); + } + + try + { + fixed (byte* pBuffer = buffer) + { + var pOffsetBuffer = pBuffer + offset; + var addressFamily = (AddressFamily)Marshal.ReadInt32((IntPtr)pOffsetBuffer); + var socketAddressSize = Marshal.ReadInt32((IntPtr)(pOffsetBuffer + 4)); + + if (buffer.Length < offset + 8 + socketAddressSize) + { + throw new ArgumentException("Buffer length is insufficient for the given SocketAddress size.", nameof(buffer)); + } + + socketAddress = new SocketAddress(addressFamily, socketAddressSize); + + for (var i = 0; i < socketAddressSize - 2; i++) + { + socketAddress[i + 2] = *(pOffsetBuffer + 8 + i); + } + + return 8 + offset + socketAddressSize; + } + } + catch (ArgumentNullException ex) + { + throw new InvalidOperationException("An argument provided to the method is null.", ex); + } + catch (ArgumentException ex) + { + throw new InvalidOperationException("An argument provided to the method is invalid.", ex); + } + catch (Exception ex) + { + throw new InvalidOperationException("An unexpected error occurred while processing the buffer.", ex); + } + } + + /// + /// 将ReadOnlyMemory转换为SocketAddress + /// + /// + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe int ByteToSocketAddress(ReadOnlyMemory buffer, int offset, out SocketAddress socketAddress) + { + if (buffer.Length < 8) + { + throw new ArgumentException("Buffer length is insufficient. It must be at least 8 bytes.", nameof(buffer)); + } + + try + { + fixed (byte* pBuffer = buffer.Span) + { + var pOffsetBuffer = pBuffer + offset; + var addressFamily = (AddressFamily)Marshal.ReadInt32((IntPtr)pOffsetBuffer); + var socketAddressSize = Marshal.ReadInt32((IntPtr)(pOffsetBuffer + 4)); + + if (buffer.Length < offset + 8 + socketAddressSize) + { + throw new ArgumentException("Buffer length is insufficient for the given SocketAddress size.", nameof(buffer)); + } + + socketAddress = new SocketAddress(addressFamily, socketAddressSize); + + for (var i = 0; i < socketAddressSize - 2; i++) + { + socketAddress[i + 2] = *(pOffsetBuffer + 8 + i); + } + + return 8 + offset + socketAddressSize; + } + } + catch (ArgumentNullException ex) + { + throw new InvalidOperationException("An argument provided to the method is null.", ex); + } + catch (ArgumentException ex) + { + throw new InvalidOperationException("An argument provided to the method is invalid.", ex); + } + catch (Exception ex) + { + throw new InvalidOperationException("An unexpected error occurred while processing the buffer.", ex); + } + } + + /// + /// 根据SocketAddress获得IPEndPoint + /// + /// + /// + /// + public static unsafe IPEndPoint GetIPEndPoint(this SocketAddress socketAddress) + { + switch (socketAddress.Family) + { + case AddressFamily.InterNetwork: + { + var ipBytes = new byte[4]; + for (var i = 0; i < 4; i++) + { + ipBytes[i] = socketAddress[4 + i]; + } + var port = (socketAddress[2] << 8) + socketAddress[3]; + var ip = new IPAddress(ipBytes); + return new IPEndPoint(ip, port); + } + case AddressFamily.InterNetworkV6: + { + var ipBytes = new byte[16]; + Span socketAddressSpan = stackalloc byte[28]; + + for (var i = 0; i < 28; i++) + { + socketAddressSpan[i] = socketAddress[i]; + } + + fixed (byte* pSocketAddress = socketAddressSpan) + { + for (var i = 0; i < 16; i++) + { + ipBytes[i] = *(pSocketAddress + 8 + i); + } + + var port = (*(pSocketAddress + 2) << 8) + *(pSocketAddress + 3); + var scopeId = Marshal.ReadInt64((IntPtr)(pSocketAddress + 24)); + var ip = new IPAddress(ipBytes, scopeId); + return new IPEndPoint(ip, port); + } + } + default: + { + throw new NotSupportedException("Address family not supported."); + } + } + } +#endif + /// + /// 获取本机所有网络适配器的IP地址。 + /// + /// IP地址数组。 + public static string[] GetAddressIPs() + { + var list = new List(); + foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces()) + { + // 仅考虑以太网类型的网络适配器 + if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet) + { + continue; + } + + foreach (var add in networkInterface.GetIPProperties().UnicastAddresses) + { + list.Add(add.Address.ToString()); + } + } + + return list.ToArray(); + } + + /// + /// 将主机名和端口号转换为 实例。 + /// + /// 主机名。 + /// 端口号。 + /// 实例。 + public static IPEndPoint ToIPEndPoint(string host, int port) + { + return new IPEndPoint(IPAddress.Parse(host), port); + } + + /// + /// 将地址字符串转换为 实例。 + /// + /// 地址字符串,格式为 "主机名:端口号"。 + /// 实例。 + public static IPEndPoint ToIPEndPoint(string address) + { + var index = address.LastIndexOf(':'); + var host = address.Substring(0, index); + var p = address.Substring(index + 1); + var port = int.Parse(p); + return ToIPEndPoint(host, port); + } + + /// + /// 将 实例转换为字符串表示形式。 + /// + /// 实例。 + /// 表示 的字符串。 + public static string IPEndPointToStr(this IPEndPoint self) + { + return $"{self.Address}:{self.Port}"; + } + + /// + /// 针对 Windows 平台设置UDP连接重置选项。 + /// + /// 要设置选项的 实例。 + public static void SetSioUdpConnReset(this Socket socket) + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return; + } + + /* + 目前这个问题只有Windows下才会出现。 + 服务器端在发送数据时捕获到了一个异常, + 这个异常导致原因应该是远程客户端的UDP监听已停止导致数据发送出错。 + 按理说UDP是无连接的,报这个异常是不合理的 + 这个异常让整UDP的服务监听也停止了。 + 这样就因为一个客户端的数据发送无法到达而导致了服务挂了,所有客户端都无法与服务器通信了 + 想详细了解看下https://blog.csdn.net/sunzhen6251/article/details/124168805*/ + const uint IOC_IN = 0x80000000; + const uint IOC_VENDOR = 0x18000000; + const int SIO_UDP_CONNRESET = unchecked((int) (IOC_IN | IOC_VENDOR | 12)); + + socket.IOControl(SIO_UDP_CONNRESET, new[] {Convert.ToByte(false)}, null); + } + + /// + /// 将 Socket 缓冲区大小设置为操作系统限制。 + /// + /// 要设置缓冲区大小的 Socket。 + public static void SetSocketBufferToOsLimit(this Socket socket) + { + socket.SetReceiveBufferToOSLimit(); + socket.SetSendBufferToOSLimit(); + } + + /// + /// 将 Socket 接收缓冲区大小设置为操作系统限制。 + /// 尝试增加接收缓冲区大小的次数 = 默认 + 最大增加 100 MB。 + /// + /// 要设置接收缓冲区大小的 Socket。 + /// 每次增加的步长大小。 + /// 尝试增加缓冲区大小的次数。 + public static void SetReceiveBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000) + { + // setting a too large size throws a socket exception. + // so let's keep increasing until we encounter it. + for (int i = 0; i < attempts; ++i) + { + // increase in 1 KB steps + try + { + socket.ReceiveBufferSize += stepSize; + } + catch (SocketException) + { + break; + } + } + } + + /// + /// 将 Socket 发送缓冲区大小设置为操作系统限制。 + /// 尝试增加发送缓冲区大小的次数 = 默认 + 最大增加 100 MB。 + /// + /// 要设置发送缓冲区大小的 Socket。 + /// 每次增加的步长大小。 + /// 尝试增加缓冲区大小的次数。 + public static void SetSendBufferToOSLimit(this Socket socket, int stepSize = 1024, int attempts = 100_000) + { + // setting a too large size throws a socket exception. + // so let's keep increasing until we encounter it. + for (var i = 0; i < attempts; ++i) + { + // increase in 1 KB steps + try + { + socket.SendBufferSize += stepSize; + } + catch (SocketException) + { + break; + } + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/NetworkHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/NetworkHelper.cs.meta new file mode 100644 index 00000000..7e3f70c2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/NetworkHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f35b5f3e69dae431982e69500c1c97c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/RandomHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/RandomHelper.cs new file mode 100644 index 00000000..a91b3604 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/RandomHelper.cs @@ -0,0 +1,293 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace Fantasy.Helper +{ + /// + /// 随机数操作助手类,提供各种随机数生成和操作方法。 + /// + public static partial class RandomHelper + { + private static readonly Random Random = new Random(); + private static readonly byte[] Byte8 = new byte[8]; + private static readonly byte[] Byte2 = new byte[2]; + + /// + /// 生成一个随机的无符号 64 位整数。 + /// + /// 无符号 64 位整数。 + public static ulong RandUInt64() + { + Random.NextBytes(Byte8); + return BitConverter.ToUInt64(Byte8, 0); + } + + /// + /// 生成一个随机的 64 位整数。 + /// + /// 64 位整数。 + public static long RandInt64() + { + Random.NextBytes(Byte8); + return BitConverter.ToInt64(Byte8, 0); + } + + /// + /// 生成一个随机的无符号 32 位整数。 + /// + /// 无符号 32 位整数。 + public static uint RandUInt32() + { + return (uint) Random.Next(); + } + + /// + /// 生成一个随机的无符号 16 位整数。 + /// + /// 无符号 16 位整数。 + public static ushort RandUInt16() + { + Random.NextBytes(Byte2); + return BitConverter.ToUInt16(Byte2, 0); + } + + /// + /// 在指定范围内生成一个随机整数(包含下限,不包含上限)。 + /// + /// 下限。 + /// 上限。 + /// 生成的随机整数。 + public static int RandomNumber(int lower, int upper) + { + return Random.Next(lower, upper); + } + + /// + /// 生成一个随机的布尔值。 + /// + /// 随机的布尔值。 + public static bool RandomBool() + { + return Random.Next(2) == 0; + } + + /// + /// 从数组中随机选择一个元素。 + /// + /// 数组元素的类型。 + /// 要选择的数组。 + /// 随机选择的数组元素。 + public static T RandomArray(this T[] array) + { + return array[RandomNumber(0, array.Count())]; + } + + /// + /// 从列表中随机选择一个元素。 + /// + /// 列表元素的类型。 + /// 要选择的列表。 + /// 随机选择的列表元素。 + public static T RandomArray(this List array) + { + return array[RandomNumber(0, array.Count())]; + } + + /// + /// 打乱列表中元素的顺序。 + /// + /// 列表元素的类型。 + /// 要打乱顺序的列表。 + public static void BreakRank(List arr) + { + if (arr == null || arr.Count < 2) + { + return; + } + + for (var i = 0; i < arr.Count / 2; i++) + { + var index = Random.Next(0, arr.Count); + (arr[index], arr[arr.Count - index - 1]) = (arr[arr.Count - index - 1], arr[index]); + } + } + + /// + /// 生成一个介于 0 和 1 之间的随机单精度浮点数。 + /// + /// 随机单精度浮点数。 + public static float RandFloat01() + { + var value = Random.NextDouble(); + return (float) value; + } + + private static int Rand(int n) + { + var rd = new Random(); + // 注意,返回值是左闭右开,所以maxValue要加1 + return rd.Next(1, n + 1); + } + + /// + /// 根据权重随机选择一个索引。 + /// + /// 权重数组,每个元素表示相应索引的权重。 + /// 随机选择的索引值。 + public static int RandomByWeight(int[] weights) + { + var sum = weights.Sum(); + var numberRand = Rand(sum); + var sumTemp = 0; + for (var i = 0; i < weights.Length; i++) + { + sumTemp += weights[i]; + if (numberRand <= sumTemp) + { + return i; + } + } + + return -1; + } + + /// + /// 根据固定概率随机选择一个索引,即某个数值上限内随机多少次。 + /// + /// 概率数组,每个元素表示相应索引的概率。 + /// 随机选择的索引值。 + public static int RandomByFixedProbability(int[] args) + { + var argCount = args.Length; + var sum = args.Sum(); + var random = Random.NextDouble() * sum; + while (sum > random) + { + sum -= args[argCount - 1]; + argCount--; + } + + return argCount; + } + + /// + /// 返回随机数。 + /// + /// 是否包含负数。 + /// 返回一个随机的单精度浮点数。 + public static float NextFloat(bool containNegative = false) + { + float f; + var buffer = new byte[4]; + if (containNegative) + { + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= float.MinValue && f < float.MaxValue) == false); + + return f; + } + + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= 0 && f < float.MaxValue) == false); + + return f; + } + + /// + /// 返回一个小于所指定最大值的非负随机数。 + /// + /// 要生成的随机数的上限(随机数不能取该上限值)。 maxValue 必须大于或等于零。 + /// 大于等于零且小于 maxValue 的单精度浮点数,即:返回值的范围通常包括零但不包括 maxValue。 不过,如果 maxValue 等于零,则返回 maxValue。 + public static float NextFloat(float maxValue) + { + if (maxValue.Equals(0)) + { + return maxValue; + } + + if (maxValue < 0) + { + throw new ArgumentOutOfRangeException("“maxValue”必须大于 0。", "maxValue"); + } + + float f; + var buffer = new byte[4]; + + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= 0 && f < maxValue) == false); + + return f; + } + + /// + /// 返回一个指定范围内的随机数。 + /// + /// 返回的随机数的下界(随机数可取该下界值)。 + /// 返回的随机数的上界(随机数不能取该上界值)。 maxValue 必须大于或等于 minValue。 + /// 一个大于等于 minValue 且小于 maxValue 的单精度浮点数,即:返回的值范围包括 minValue 但不包括 maxValue。 如果 minValue 等于 maxValue,则返回 minValue。 + public static float NextFloat(float minValue, float maxValue) + { + if (minValue.Equals(maxValue)) + { + return minValue; + } + + if (minValue > maxValue) + { + throw new ArgumentOutOfRangeException("“minValue”不能大于 maxValue。", "minValue"); + } + + float f; + var buffer = new byte[4]; + + do + { + Random.NextBytes(buffer); + f = BitConverter.ToSingle(buffer, 0); + } while ((f >= minValue && f < maxValue) == false); + + return f; + } + + /// + /// 在指定的矩形区域内随机生成一个二维向量位置。 + /// + /// X轴最小值。 + /// X轴最大值。 + /// Y轴最小值。 + /// Y轴最大值。 + /// 随机生成的二维向量位置。 + public static Vector2 NextVector2(float minX, float maxX, float minY, float maxY) + { + return new Vector2(NextFloat(minX, maxX), NextFloat(minY, maxY)); + } + + /// + /// 生成指定长度的随机数字代码。 + /// + /// 数字代码的长度。 + /// 生成的随机数字代码。 + public static string RandomNumberCode(int len = 6) + { + int num = 0; + for (int i = 0; i < len; i++) + { + int number = RandomNumber(0, 10); + num = num * 10 + number; + } + + return num.ToString(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/RandomHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/RandomHelper.cs.meta new file mode 100644 index 00000000..bc0e9e49 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/RandomHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5ca1a2a2ac7a7472ab9c07166a4e471a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/SocketHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/SocketHelper.cs new file mode 100644 index 00000000..15027c55 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/SocketHelper.cs @@ -0,0 +1,74 @@ +#if !FANTASY_WEBGL +using System.Net; +using System.Net.Sockets; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Helper +{ + /// + /// Socket帮助类 + /// + public static partial class SocketHelper + { + // always pass the same IPEndPointNonAlloc instead of allocating a new + // one each time. + // + // use IPEndPointNonAlloc.temp to get the latest SocketAdddress written + // by ReceiveFrom_Internal! + // + // IMPORTANT: .temp will be overwritten in next call! + // hash or manually copy it if you need to store it, e.g. + // when adding a new connection. + public static int ReceiveFrom_NonAlloc( + this Socket socket, + byte[] buffer, + int offset, + int size, + SocketFlags socketFlags, + EndPoint remoteEndPoint) + { + // call ReceiveFrom with IPEndPointNonAlloc. + // need to wrap this in ReceiveFrom_NonAlloc because it's not + // obvious that IPEndPointNonAlloc.Create does NOT create a new + // IPEndPoint. it saves the result in IPEndPointNonAlloc.temp! +#if FANTASY_UNITY + EndPoint casted = remoteEndPoint; + return socket.ReceiveFrom(buffer, offset, size, socketFlags, ref casted); +#else + return socket.ReceiveFrom(buffer, offset, size, socketFlags, ref remoteEndPoint); +#endif + } + + // same as above, different parameters + public static int ReceiveFrom_NonAlloc(this Socket socket, byte[] buffer, ref EndPoint remoteEndPoint) + { +#if UNITY + EndPoint casted = remoteEndPoint; + return socket.ReceiveFrom(buffer, ref casted); +#else + return socket.ReceiveFrom(buffer, ref remoteEndPoint); +#endif + + } + + // SendTo allocates too: + // https://github.com/mono/mono/blob/f74eed4b09790a0929889ad7fc2cf96c9b6e3757/mcs/class/System/System.Net.Sockets/Socket.cs#L2240 + // -> the allocation is in EndPoint.Serialize() + // NOTE: technically this function isn't necessary. + // could just pass IPEndPointNonAlloc. + // still good for strong typing. + //public static int SendTo_NonAlloc( + // this Socket socket, + // byte[] buffer, + // int offset, + // int size, + // SocketFlags socketFlags, + // IPEndPointNonAlloc remoteEndPoint) + //{ + // EndPoint casted = remoteEndPoint; + // return socket.SendTo(buffer, offset, size, socketFlags, casted); + //} + } +} +#endif + + diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/SocketHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/SocketHelper.cs.meta new file mode 100644 index 00000000..d0fad2da --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/SocketHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54d75f1a06d9144e482ec46a67f2cfeb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/TimeHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/TimeHelper.cs new file mode 100644 index 00000000..ec6ff4df --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/TimeHelper.cs @@ -0,0 +1,78 @@ +using System; +#if FANTASY_UNITY +using UnityEngine; +#endif + +namespace Fantasy.Helper +{ + /// + /// 提供与时间相关的帮助方法。 + /// + public static partial class TimeHelper + { + /// + /// 一小时的毫秒值。 + /// + public const long Hour = 3600000; + /// + /// 一分钟的毫秒值。 + /// + public const long Minute = 60000; + /// + /// 一天的毫秒值。 + /// + public const long OneDay = 86400000; + // 1970年1月1日的Ticks + private const long Epoch = 621355968000000000L; + private static readonly DateTime Dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + /// + /// 获取当前时间的毫秒数,从1970年1月1日开始计算。 + /// + public static long Now => (DateTime.UtcNow.Ticks - Epoch) / 10000; +#if FANTASY_UNITY || FANTASY_CONSOLE + /// + /// 与服务器时间的偏差。 + /// + public static long TimeDiff; + /// + /// 获取当前服务器时间的毫秒数,加上与服务器时间的偏差。 + /// + public static long ServerNow => Now + TimeDiff; +#if FANTASY_UNITY + /// + /// 获取当前Unity运行的总时间的毫秒数。 + /// + public static long UnityNow => (long) (Time.time * 1000); +#endif +#endif + /// + /// 将日期时间转换为毫秒数,从1970年1月1日开始计算。 + /// + /// 要转换的日期时间。 + /// 转换后的毫秒数。 + public static long Transition(this DateTime d) + { + return (d.Ticks - Epoch) / 10000; + } + + /// + /// 将毫秒数转换为日期时间。 + /// + /// 要转换的毫秒数。 + /// 转换后的日期时间。 + public static DateTime Transition(this long timeStamp) + { + return Dt1970.AddTicks(timeStamp); + } + + /// + /// 将毫秒数转换为本地时间的日期时间。 + /// + /// 要转换的毫秒数。 + /// 转换后的本地时间的日期时间。 + public static DateTime TransitionLocal(this long timeStamp) + { + return Dt1970.AddTicks(timeStamp).ToLocalTime(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/TimeHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/TimeHelper.cs.meta new file mode 100644 index 00000000..3a8d9624 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/TimeHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3937c5cea56304a79b138c980c91b79b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WebSocketHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WebSocketHelper.cs new file mode 100644 index 00000000..822db064 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WebSocketHelper.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Fantasy.Helper +{ + /// + /// WebSocket帮助类 + /// + public static partial class WebSocketHelper + { + /// + /// 根据字符串获取WebSocket的连接地址 + /// + /// 目标服务器地址格式为:127.0.0.1:2000 + /// 目标服务器是否为加密连接也就是https + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string GetWebSocketAddress(string address, bool isHttps) + { + var addressSplit = address.Split(':'); + if (addressSplit.Length != 2) + { + throw new FormatException("Invalid format"); + } + + var ipString = addressSplit[0]; + var portString = addressSplit[1]; + + if (!int.TryParse(portString, out var port) || port < 0 || port > 65535) + { + throw new FormatException("Invalid port number"); + } + + return isHttps ? $"wss://{ipString}:{portString}" : $"ws://{ipString}:{portString}"; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WebSocketHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WebSocketHelper.cs.meta new file mode 100644 index 00000000..66d58c17 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WebSocketHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 43d82d55edae640d69ed83a832d4dd3e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WinPeriod.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WinPeriod.cs new file mode 100644 index 00000000..a1a5aca6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WinPeriod.cs @@ -0,0 +1,24 @@ +using System.Runtime.InteropServices; + +namespace Fantasy.Helper +{ + /// + /// 精度设置 + /// + public static partial class WinPeriod + { + // 一般默认的精度不止1毫秒(不同操作系统有所不同),需要调用timeBeginPeriod与timeEndPeriod来设置精度 + [DllImport("winmm")] + private static extern void timeBeginPeriod(int t); + /// + /// 针对Windows平台设置精度 + /// + public static void Initialize() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + timeBeginPeriod(1); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WinPeriod.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WinPeriod.cs.meta new file mode 100644 index 00000000..5cfeef05 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Helper/WinPeriod.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 20f6f771c52ad42f0a0e74df662f45cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory.meta new file mode 100644 index 00000000..e70ab4f0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ded441da24c074aeca67d4b36b990070 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/EntityIdFactory.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/EntityIdFactory.cs new file mode 100644 index 00000000..64fe9a56 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/EntityIdFactory.cs @@ -0,0 +1,150 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.IdFactory +{ + /// + /// 表示一个唯一实体的ID。 + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct EntityIdStruct + { + // EntityId:39 + 8 + 8 + 18 = 64 + // +-------------------+--------------------------+-----------------------+------------------------------------+ + // | time(30) 最大34年 | SceneId(8) 最多255个Scene | WordId(8) 最多255个世界 | sequence(18) 每秒每个进程能生产262143个 + // +-------------------+--------------------------+-----------------------+------------------------------------+ + public uint Time { get; private set; } + public uint SceneId { get; private set; } + public byte WordId { get; private set; } + public uint Sequence { get; private set; } + + public const uint MaskSequence = 0x3FFFF; + public const uint MaskSceneId = 0xFF; + public const uint MaskWordId = 0xFF; + public const uint MaskTime = 0x3FFFFFFF; + + /// + /// RuntimeIdStruct(如果超过下面参数的设定该ID会失效)。 + /// + /// time不能超过1073741823 + /// sceneId不能超过255 + /// wordId不能超过255 + /// sequence不能超过262143 + public EntityIdStruct(uint time, uint sceneId, byte wordId, uint sequence) + { + // 因为都是在配置表里拿到参数、所以这个不做边界判定、能节省一点点性能。 + Time = time; + SceneId = sceneId; + WordId = wordId; + Sequence = sequence; + } + + public static implicit operator long(EntityIdStruct entityIdStruct) + { + ulong result = 0; + result |= entityIdStruct.Sequence; + result |= (ulong)entityIdStruct.WordId << 18; + result |= (ulong)(entityIdStruct.SceneId % (entityIdStruct.WordId * 1000)) << 26; + result |= (ulong)entityIdStruct.Time << 34; + return (long)result; + } + + public static implicit operator EntityIdStruct(long entityId) + { + var result = (ulong) entityId; + var entityIdStruct = new EntityIdStruct + { + Sequence = (uint)(result & MaskSequence) + }; + result >>= 18; + entityIdStruct.WordId = (byte)(result & MaskWordId); + result >>= 8; + entityIdStruct.SceneId = (uint)(result & MaskSceneId) + (uint)entityIdStruct.WordId * 1000; + result >>= 8; + entityIdStruct.Time = (uint)(result & MaskTime); + return entityIdStruct; + } + } + + public sealed class EntityIdFactory + { + private readonly uint _sceneId; + private readonly byte _worldId; + + private uint _lastTime; + private uint _lastSequence; + private static readonly long Epoch1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; + private static readonly long EpochThisYear = new DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000 - Epoch1970; + + private EntityIdFactory() { } + + public EntityIdFactory(uint sceneId, byte worldId) + { + switch (sceneId) + { + case > 255255: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be greater than 255255"); + } + case < 1001: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be less than 1001"); + } + default: + { + _sceneId = sceneId; + _worldId = worldId; + break; + } + } + } + + public long Create + { + get + { + var time = (uint)((TimeHelper.Now - EpochThisYear) / 1000); + + if (time > _lastTime) + { + _lastTime = time; + _lastSequence = 0; + } + else if (++_lastSequence > EntityIdStruct.MaskSequence - 1) + { + _lastTime++; + _lastSequence = 0; + } + + return new EntityIdStruct(time, _sceneId, _worldId, _lastSequence); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetTime(ref long entityId) + { + var result = (ulong)entityId >> 34; + return (uint)(result & EntityIdStruct.MaskTime); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetSceneId(ref long entityId) + { + var result = (ulong)entityId >> 18; + var worldId = (uint)(result & EntityIdStruct.MaskWordId) * 1000; + result >>= 8; + return (uint)(result & EntityIdStruct.MaskSceneId) + worldId; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte GetWorldId(ref long entityId) + { + var result = (ulong)entityId >> 18; + return (byte)(result & EntityIdStruct.MaskWordId); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/EntityIdFactory.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/EntityIdFactory.cs.meta new file mode 100644 index 00000000..713014ff --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/EntityIdFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70e47f815e1414886bee3c9790d0f316 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/RuntimeIdFactory.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/RuntimeIdFactory.cs new file mode 100644 index 00000000..6c89b21b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/RuntimeIdFactory.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.IdFactory +{ + /// + /// 表示一个运行时的ID。 + /// + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct RuntimeIdStruct + { + // RuntimeId:23 + 8 + 8 + 25 = 64 + // +-------------------+--------------------------+-----------------------+--------------------------------------+ + // | time(23) 最大60天 | SceneId(8) 最多255个Scene | WordId(8) 最多255个世界 | sequence(25) 每秒每个进程能生产33554431个 + // +-------------------+--------------------------+-----------------------+--------------------------------------+ + public uint Time { get; private set; } + public uint SceneId { get; private set; } + public byte WordId { get; private set; } + public uint Sequence { get; private set; } + + public const uint MaskSequence = 0x1FFFFFF; + public const uint MaskSceneId = 0xFF; + public const uint MaskWordId = 0xFF; + public const uint MaskTime = 0x7FFFFF; + + /// + /// RuntimeIdStruct(如果超过下面参数的设定该ID会失效)。 + /// + /// time不能超过8388607 + /// sceneId不能超过255 + /// wordId不能超过255 + /// sequence不能超过33554431 + public RuntimeIdStruct(uint time, uint sceneId, byte wordId, uint sequence) + { + // 因为都是在配置表里拿到参数、所以这个不做边界判定、能节省一点点性能。 + Time = time; + SceneId = sceneId; + WordId = wordId; + Sequence = sequence; + } + + public static implicit operator long(RuntimeIdStruct runtimeIdStruct) + { + ulong result = runtimeIdStruct.Sequence; + result |= (ulong)runtimeIdStruct.WordId << 25; + result |= (ulong)(runtimeIdStruct.SceneId % (runtimeIdStruct.WordId * 1000)) << 33; + result |= (ulong)runtimeIdStruct.Time << 41; + return (long)result; + } + + public static implicit operator RuntimeIdStruct(long runtimeId) + { + var result = (ulong)runtimeId; + var runtimeIdStruct = new RuntimeIdStruct + { + Sequence = (uint)(result & MaskSequence) + }; + result >>= 25; + runtimeIdStruct.WordId = (byte)(result & MaskWordId); + result >>= 8; + runtimeIdStruct.SceneId = (uint)(result & MaskSceneId) + (uint)runtimeIdStruct.WordId * 1000; + result >>= 8; + runtimeIdStruct.Time = (uint)(result & MaskTime); + return runtimeIdStruct; + } + } + + public sealed class RuntimeIdFactory + { + private readonly uint _sceneId; + private readonly byte _worldId; + + private uint _lastTime; + private uint _lastSequence; + private readonly long _epochNow; + private readonly long _epoch1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; + + private RuntimeIdFactory() { } + + public RuntimeIdFactory(uint sceneId, byte worldId) : this(TimeHelper.Now, sceneId, worldId) { } + + public RuntimeIdFactory(long epochNow, uint sceneId, byte worldId) + { + switch (sceneId) + { + case > 255255: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be greater than 255255"); + } + case < 1001: + { + throw new NotSupportedException($"sceneId:{sceneId} cannot be less than 1001"); + } + default: + { + _sceneId = sceneId; + _worldId = worldId; + _epochNow = epochNow - _epoch1970; + break; + } + } + } + + public long Create + { + get + { + var time = (uint)((TimeHelper.Now - _epochNow) / 1000); + + if (time > _lastTime) + { + _lastTime = time; + _lastSequence = 0; + } + else if (++_lastSequence > RuntimeIdStruct.MaskSequence - 1) + { + _lastTime++; + _lastSequence = 0; + } + + return new RuntimeIdStruct(time, _sceneId, _worldId, _lastSequence); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetTime(ref long runtimeId) + { + var result = (ulong)runtimeId >> 41; + return (uint)(result & RuntimeIdStruct.MaskTime); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint GetSceneId(ref long runtimeId) + { + var result = (ulong)runtimeId >> 25; + var worldId = (uint)(result & RuntimeIdStruct.MaskWordId) * 1000; + result >>= 8; + return (uint)(result & RuntimeIdStruct.MaskSceneId) + worldId; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte GetWorldId(ref long runtimeId) + { + var result = (ulong)runtimeId >> 25; + return (byte)(result & RuntimeIdStruct.MaskWordId); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/RuntimeIdFactory.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/RuntimeIdFactory.cs.meta new file mode 100644 index 00000000..f7a3f0c1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/IdFactory/RuntimeIdFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28256b071ab2e491ca9622c5879e14a9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/InnerErrorCode.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/InnerErrorCode.cs new file mode 100644 index 00000000..3510b76d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/InnerErrorCode.cs @@ -0,0 +1,31 @@ +namespace Fantasy.Network +{ + /// + /// 定义 Fantasy 框架中的内部错误代码。 + /// + public class InnerErrorCode + { + private InnerErrorCode() { } + /// + /// 表示 Rpc 消息发送失败的错误代码。 + /// + public const uint ErrRpcFail = 100000002; + /// + /// 表示未找到 Route 消息的错误代码。 + /// + public const uint ErrNotFoundRoute = 100000003; + + /// + /// 表示发送 Route 消息超时的错误代码。 + /// + public const uint ErrRouteTimeout = 100000004; + /// + /// 表示未找到实体的错误代码。 + /// + public const uint ErrEntityNotFound = 100000008; + /// + /// 表示传送过程中发生错误的错误代码。 + /// + public const uint ErrTransfer = 100000009; + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/InnerErrorCode.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/InnerErrorCode.cs.meta new file mode 100644 index 00000000..55bf9bc1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/InnerErrorCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 20d260b595ed246d3804b2c64e541cd9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log.meta new file mode 100644 index 00000000..3ff8e73b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c03babc2b23544aa391f909918cd152e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ConsoleLog.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ConsoleLog.cs new file mode 100644 index 00000000..0d57e229 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ConsoleLog.cs @@ -0,0 +1,144 @@ +#if FANTASY_NET +using Fantasy.Platform.Net; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy; + +/// +/// 标准的控制台Log +/// +public sealed class ConsoleLog : ILog +{ + /// + /// 初始化方法 + /// + /// + public void Initialize(ProcessMode processMode) { } + + /// + /// 记录跟踪级别的日志消息。 + /// + /// 日志消息。 + public void Trace(string message) + { + Console.ForegroundColor = ConsoleColor.White; + Console.WriteLine(message); + } + + /// + /// 记录警告级别的日志消息。 + /// + /// 日志消息。 + public void Warning(string message) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine(message); + } + + /// + /// 记录信息级别的日志消息。 + /// + /// 日志消息。 + public void Info(string message) + { + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(message); + } + + /// + /// 记录调试级别的日志消息。 + /// + /// 日志消息。 + public void Debug(string message) + { + Console.ForegroundColor = ConsoleColor.DarkGreen; + Console.WriteLine(message); + } + + /// + /// 记录错误级别的日志消息。 + /// + /// 日志消息。 + public void Error(string message) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine(message); + } + + /// + /// 记录严重错误级别的日志消息。 + /// + /// 日志消息。 + public void Fatal(string message) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine(message); + } + + /// + /// 记录跟踪级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Trace(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.White; + Console.WriteLine(message, args); + } + + /// + /// 记录警告级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Warning(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine(message, args); + } + + /// + /// 记录信息级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Info(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.Gray; + Console.WriteLine(message, args); + } + + /// + /// 记录调试级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Debug(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.DarkGreen; + Console.WriteLine(message, args); + } + + /// + /// 记录错误级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Error(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine(message, args); + } + + /// + /// 记录严重错误级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public void Fatal(string message, params object[] args) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine(message, args); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ConsoleLog.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ConsoleLog.cs.meta new file mode 100644 index 00000000..a61215aa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ConsoleLog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc11e6d3846d64f8799313ac7b5c7ffd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ILog.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ILog.cs new file mode 100644 index 00000000..b01e8579 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ILog.cs @@ -0,0 +1,74 @@ +#if FANTASY_NET +using Fantasy.Platform.Net; +#endif +namespace Fantasy +{ + /// + /// 定义日志记录功能的接口。 + /// + public interface ILog + { +#if FANTASY_NET + /// + /// 初始化 + /// + /// + void Initialize(ProcessMode processMode); +#endif + /// + /// 记录跟踪级别的日志消息。 + /// + /// 日志消息。 + void Trace(string message); + /// + /// 记录警告级别的日志消息。 + /// + /// 日志消息。 + void Warning(string message); + /// + /// 记录信息级别的日志消息。 + /// + /// 日志消息。 + void Info(string message); + /// + /// 记录调试级别的日志消息。 + /// + /// 日志消息。 + void Debug(string message); + /// + /// 记录错误级别的日志消息。 + /// + /// 日志消息。 + void Error(string message); + /// + /// 记录跟踪级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Trace(string message, params object[] args); + /// + /// 记录警告级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Warning(string message, params object[] args); + /// + /// 记录信息级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Info(string message, params object[] args); + /// + /// 记录调试级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Debug(string message, params object[] args); + /// + /// 记录错误级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + void Error(string message, params object[] args); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ILog.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ILog.cs.meta new file mode 100644 index 00000000..f70cb9fa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/ILog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 16ffac81f7ac6485ebd425c88ada6c96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/Log.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/Log.cs new file mode 100644 index 00000000..8069fffb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/Log.cs @@ -0,0 +1,189 @@ +using System; +using System.Diagnostics; +#if FANTASY_NET +using Fantasy.Platform.Net; +#endif + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy +{ + /// + /// 提供日志记录功能的静态类。 + /// + public static class Log + { + private static ILog _logCore; + private static bool _isRegister; +#if FANTASY_NET + /// + /// 初始化Log系统 + /// + public static void Initialize() + { + if (!_isRegister) + { + Register(new ConsoleLog()); + return; + } + + var processMode = ProcessMode.None; + + switch (ProcessDefine.Options.Mode) + { + case "Develop": + { + processMode = ProcessMode.Develop; + break; + } + case "Release": + { + processMode = ProcessMode.Release; + break; + } + } + + _logCore.Initialize(processMode); + } +#endif + /// + /// 注册一个日志系统 + /// + /// + public static void Register(ILog log) + { + if (_isRegister) + { + return; + } + + _logCore = log; + _isRegister = true; + } + + /// + /// 记录跟踪级别的日志消息。 + /// + /// 日志消息。 + public static void Trace(string msg) + { + var st = new StackTrace(1, true); + _logCore.Trace($"{msg}\n{st}"); + } + + /// + /// 记录调试级别的日志消息。 + /// + /// 日志消息。 + public static void Debug(string msg) + { + _logCore.Debug(msg); + } + + /// + /// 记录信息级别的日志消息。 + /// + /// 日志消息。 + public static void Info(string msg) + { + _logCore.Info(msg); + } + + /// + /// 记录跟踪级别的日志消息,并附带调用栈信息。 + /// + /// 日志消息。 + public static void TraceInfo(string msg) + { + var st = new StackTrace(1, true); + _logCore.Trace($"{msg}\n{st}"); + } + + /// + /// 记录警告级别的日志消息。 + /// + /// 日志消息。 + public static void Warning(string msg) + { + _logCore.Warning(msg); + } + + /// + /// 记录错误级别的日志消息,并附带调用栈信息。 + /// + /// 日志消息。 + public static void Error(string msg) + { + var st = new StackTrace(1, true); + _logCore.Error($"{msg}\n{st}"); + } + + /// + /// 记录异常的错误级别的日志消息,并附带调用栈信息。 + /// + /// 异常对象。 + public static void Error(Exception e) + { + if (e.Data.Contains("StackTrace")) + { + _logCore.Error($"{e.Data["StackTrace"]}\n{e}"); + return; + } + var str = e.ToString(); + _logCore.Error(str); + } + + /// + /// 记录跟踪级别的格式化日志消息,并附带调用栈信息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Trace(string message, params object[] args) + { + var st = new StackTrace(1, true); + _logCore.Trace($"{string.Format(message, args)}\n{st}"); + } + + /// + /// 记录警告级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Warning(string message, params object[] args) + { + _logCore.Warning(string.Format(message, args)); + } + + /// + /// 记录信息级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Info(string message, params object[] args) + { + _logCore.Info(string.Format(message, args)); + } + + /// + /// 记录调试级别的格式化日志消息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Debug(string message, params object[] args) + { + _logCore.Debug(string.Format(message, args)); + } + + /// + /// 记录错误级别的格式化日志消息,并附带调用栈信息。 + /// + /// 日志消息模板。 + /// 格式化参数。 + public static void Error(string message, params object[] args) + { + var st = new StackTrace(1, true); + var s = string.Format(message, args) + '\n' + st; + _logCore.Error(s); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/Log.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/Log.cs.meta new file mode 100644 index 00000000..feae74a4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/Log.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 59c957edf5e8940d28d5b13e0311184e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/UnityLog.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/UnityLog.cs new file mode 100644 index 00000000..c3815287 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/UnityLog.cs @@ -0,0 +1,182 @@ +#if UNITY_EDITOR +using System; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEditorInternal; +#else +using System; +#endif + +#if FANTASY_UNITY +namespace Fantasy +{ + public class UnityLog : ILog + { + public void Trace(string msg) + { + UnityEngine.Debug.Log(msg); + } + + public void Debug(string msg) + { + UnityEngine.Debug.Log(msg); + } + + public void Info(string msg) + { + UnityEngine.Debug.Log(msg); + } + + public void Warning(string msg) + { + UnityEngine.Debug.LogWarning(msg); + } + + public void Error(string msg) + { + UnityEngine.Debug.LogError(msg); + } + + public void Error(Exception e) + { + UnityEngine.Debug.LogException(e); + } + + public void Trace(string message, params object[] args) + { + UnityEngine.Debug.LogFormat(message, args); + } + + public void Warning(string message, params object[] args) + { + UnityEngine.Debug.LogWarningFormat(message, args); + } + + public void Info(string message, params object[] args) + { + UnityEngine.Debug.LogFormat(message, args); + } + + public void Debug(string message, params object[] args) + { + UnityEngine.Debug.LogFormat(message, args); + } + + public void Error(string message, params object[] args) + { + UnityEngine.Debug.LogErrorFormat(message, args); + } + } +} +#endif + +#if UNITY_EDITOR +namespace Fantasy +{ + /// + /// 日志重定向相关的实用函数。 + /// + internal static class LogRedirection + { + [OnOpenAsset(0)] + private static bool OnOpenAsset(int instanceID, int line) + { + if (line <= 0) + { + return false; + } + + // 获取资源路径 + string assetPath = AssetDatabase.GetAssetPath(instanceID); + + // 判断资源类型 + if (!assetPath.EndsWith(".cs")) + { + return false; + } + + bool autoFirstMatch = assetPath.Contains("Log.cs") || + assetPath.Contains("UnityLog.cs"); + + var stackTrace = GetStackTrace(); + if (!string.IsNullOrEmpty(stackTrace)) + + { + if (!autoFirstMatch) + { + var fullPath = UnityEngine.Application.dataPath.Substring(0, UnityEngine.Application.dataPath.LastIndexOf("Assets", StringComparison.Ordinal)); + fullPath = $"{fullPath}{assetPath}"; + // 跳转到目标代码的特定行 + InternalEditorUtility.OpenFileAtLineExternal(fullPath.Replace('/', '\\'), line); + return true; + } + + // 使用正则表达式匹配at的哪个脚本的哪一行 + var matches = Regex.Match(stackTrace, @"\(at (.+)\)", + RegexOptions.IgnoreCase); + while (matches.Success) + { + var pathLine = matches.Groups[1].Value; + + if (!pathLine.Contains("Log.cs") && + !pathLine.Contains("UnityLog.cs")) + { + var splitIndex = pathLine.LastIndexOf(":", StringComparison.Ordinal); + // 脚本路径 + var path = pathLine.Substring(0, splitIndex); + // 行号 + line = Convert.ToInt32(pathLine.Substring(splitIndex + 1)); + var fullPath = UnityEngine.Application.dataPath.Substring(0, UnityEngine.Application.dataPath.LastIndexOf("Assets", StringComparison.Ordinal)); + fullPath = $"{fullPath}{path}"; + // 跳转到目标代码的特定行 + InternalEditorUtility.OpenFileAtLineExternal(fullPath.Replace('/', '\\'), line); + break; + } + + matches = matches.NextMatch(); + } + + return true; + } + + return false; + } + + /// + /// 获取当前日志窗口选中的日志的堆栈信息。 + /// + /// 选中日志的堆栈信息实例。 + private static string GetStackTrace() + { + // 通过反射获取ConsoleWindow类 + var consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow"); + // 获取窗口实例 + var fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", + BindingFlags.Static | + BindingFlags.NonPublic); + if (fieldInfo != null) + { + var consoleInstance = fieldInfo.GetValue(null); + if (consoleInstance != null) + if (EditorWindow.focusedWindow == (EditorWindow)consoleInstance) + { + // 获取m_ActiveText成员 + fieldInfo = consoleWindowType.GetField("m_ActiveText", + BindingFlags.Instance | + BindingFlags.NonPublic); + // 获取m_ActiveText的值 + if (fieldInfo != null) + { + var activeText = fieldInfo.GetValue(consoleInstance).ToString(); + return activeText; + } + } + } + + return null; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/UnityLog.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/UnityLog.cs.meta new file mode 100644 index 00000000..93addc63 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Log/UnityLog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a972d9201cbac4103896d0fabe482806 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network.meta new file mode 100644 index 00000000..52d3780e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3c0f4a22b15ea4a8facdf51886436af8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable.meta new file mode 100644 index 00000000..068e8010 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 804eec4fd3cf746289014cb3cfe99f10 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableHelper.cs new file mode 100644 index 00000000..098ba8a6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableHelper.cs @@ -0,0 +1,141 @@ +#if FANTASY_NET +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Platform.Net; +namespace Fantasy.Network.Route +{ + /// + /// 提供操作地址映射的辅助方法。 + /// + public static class AddressableHelper + { + // 声明一个私有静态只读列表 AddressableScenes,用于存储地址映射的场景配置信息 + private static readonly List AddressableScenes = new List(); + + static AddressableHelper() + { + // 遍历场景配置信息,筛选出地址映射类型的场景,并添加到 AddressableScenes 列表中 + foreach (var sceneConfig in SceneConfigData.Instance.List) + { + if (sceneConfig.SceneTypeString == "Addressable") + { + AddressableScenes.Add(new AddressableScene(sceneConfig)); + } + } + } + + /// + /// 添加地址映射并返回操作结果。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + /// 路由 ID。 + /// 是否锁定。 + public static async FTask AddAddressable(Scene scene, long addressableId, long routeId, bool isLock = true) + { + // 获取指定索引的地址映射场景配置信息 + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + // 调用内部路由方法,发送添加地址映射的请求并等待响应 + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableAdd_Request + { + AddressableId = addressableId, RouteId = routeId, IsLock = isLock + }); + if (response.ErrorCode != 0) + { + Log.Error($"AddAddressable error is {response.ErrorCode}"); + } + } + + /// + /// 获取地址映射的路由 ID。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + /// 地址映射的路由 ID。 + public static async FTask GetAddressableRouteId(Scene scene, long addressableId) + { + // 获取指定索引的地址映射场景配置信息 + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + // 调用内部路由方法,发送获取地址映射路由 ID 的请求并等待响应 + var response = (I_AddressableGet_Response) await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableGet_Request + { + AddressableId = addressableId + }); + // 检查响应错误码,如果为零,返回路由 ID;否则,输出错误信息并返回 0 + if (response.ErrorCode == 0) + { + return response.RouteId; + } + + Log.Error($"GetAddressable error is {response.ErrorCode} addressableId:{addressableId}"); + return 0; + } + + /// + /// 移除指定地址映射。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + public static async FTask RemoveAddressable(Scene scene, long addressableId) + { + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableRemove_Request + { + AddressableId = addressableId + }); + + if (response.ErrorCode != 0) + { + Log.Error($"RemoveAddressable error is {response.ErrorCode}"); + } + } + + /// + /// 锁定指定地址映射。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + public static async FTask LockAddressable(Scene scene, long addressableId) + { + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableLock_Request + { + AddressableId = addressableId + }); + + if (response.ErrorCode != 0) + { + Log.Error($"LockAddressable error is {response.ErrorCode}"); + } + } + + /// + /// 解锁指定地址映射。 + /// + /// 场景实例。 + /// 地址映射的唯一标识。 + /// 路由 ID。 + /// 解锁来源。 + public static async FTask UnLockAddressable(Scene scene, long addressableId, long routeId, string source) + { + var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count]; + var response = await scene.NetworkMessagingComponent.CallInnerRoute(addressableScene.RunTimeId, + new I_AddressableUnLock_Request + { + AddressableId = addressableId, + RouteId = routeId, + Source = source + }); + + if (response.ErrorCode != 0) + { + Log.Error($"UnLockAddressable error is {response.ErrorCode}"); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableHelper.cs.meta new file mode 100644 index 00000000..316c4c23 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66702f6e5c88f49ad95b95d5342dac17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableManageComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableManageComponent.cs new file mode 100644 index 00000000..8d08f083 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableManageComponent.cs @@ -0,0 +1,144 @@ +#if FANTASY_NET +using System; +using System.Collections.Generic; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.Route +{ + public class AddressableManageComponentAwakeSystem : AwakeSystem + { + protected override void Awake(AddressableManageComponent self) + { + self.AddressableLock = self.Scene.CoroutineLockComponent.Create(self.GetType().TypeHandle.Value.ToInt64()); + } + } + + public class AddressableManageComponentDestroySystem : DestroySystem + { + protected override void Destroy(AddressableManageComponent self) + { + foreach (var (_, waitCoroutineLock) in self.Locks) + { + waitCoroutineLock.Dispose(); + } + + self.Locks.Clear(); + self.Addressable.Clear(); + self.AddressableLock.Dispose(); + self.AddressableLock = null; + } + } + + public sealed class AddressableManageComponent : Entity + { + public CoroutineLock AddressableLock; + public readonly Dictionary Addressable = new(); + public readonly Dictionary Locks = new(); + + /// + /// 添加地址映射。 + /// + /// 地址映射的唯一标识。 + /// 路由 ID。 + /// 是否进行锁定。 + public async FTask Add(long addressableId, long routeId, bool isLock) + { + WaitCoroutineLock waitCoroutineLock = null; + + try + { + if (isLock) + { + waitCoroutineLock = await AddressableLock.Wait(addressableId); + } + + Addressable[addressableId] = routeId; +#if FANTASY_DEVELOP + Log.Debug($"AddressableManageComponent Add addressableId:{addressableId} routeId:{routeId}"); +#endif + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + waitCoroutineLock?.Dispose(); + } + } + + /// + /// 获取地址映射的路由 ID。 + /// + /// 地址映射的唯一标识。 + /// 地址映射的路由 ID。 + public async FTask Get(long addressableId) + { + using (await AddressableLock.Wait(addressableId)) + { + Addressable.TryGetValue(addressableId, out var routeId); + return routeId; + } + } + + /// + /// 移除地址映射。 + /// + /// 地址映射的唯一标识。 + public async FTask Remove(long addressableId) + { + using (await AddressableLock.Wait(addressableId)) + { + Addressable.Remove(addressableId); +#if FANTASY_DEVELOP + Log.Debug($"Addressable Remove addressableId: {addressableId} _addressable:{Addressable.Count}"); +#endif + } + } + + /// + /// 锁定地址映射。 + /// + /// 地址映射的唯一标识。 + public async FTask Lock(long addressableId) + { + var waitCoroutineLock = await AddressableLock.Wait(addressableId); + Locks.Add(addressableId, waitCoroutineLock); + } + + /// + /// 解锁地址映射。 + /// + /// 地址映射的唯一标识。 + /// 新的路由 ID。 + /// 解锁来源。 + public void UnLock(long addressableId, long routeId, string source) + { + if (!Locks.Remove(addressableId, out var coroutineLock)) + { + Log.Error($"Addressable unlock not found addressableId: {addressableId} Source:{source}"); + return; + } + + Addressable.TryGetValue(addressableId, out var oldAddressableId); + + if (routeId != 0) + { + Addressable[addressableId] = routeId; + } + + coroutineLock.Dispose(); +#if FANTASY_DEVELOP + Log.Debug($"Addressable UnLock key: {addressableId} oldAddressableId : {oldAddressableId} routeId: {routeId} Source:{source}"); +#endif + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableManageComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableManageComponent.cs.meta new file mode 100644 index 00000000..c23fdd02 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableManageComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b752c543b1cd44fe1956b407ec94fd6e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableMessageComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableMessageComponent.cs new file mode 100644 index 00000000..92273743 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableMessageComponent.cs @@ -0,0 +1,91 @@ +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + public class AddressableMessageComponentDestroySystem : DestroySystem + { + protected override void Destroy(AddressableMessageComponent self) + { + if (self.AddressableId != 0) + { + AddressableHelper.RemoveAddressable(self.Scene, self.AddressableId).Coroutine(); + self.AddressableId = 0; + } + } + } + + /// + /// 可寻址消息组件、挂载了这个组件可以接收Addressable消息 + /// + public sealed class AddressableMessageComponent : Entity + { + /// + /// 可寻址消息组件的唯一标识。 + /// + public long AddressableId; + + /// + /// 注册可寻址消息组件。 + /// + /// 是否进行锁定。 + public FTask Register(bool isLock = true) + { + if (Parent == null) + { + throw new Exception("AddressableRouteComponent must be mounted under a component"); + } + + AddressableId = Parent.Id; + + if (AddressableId == 0) + { + throw new Exception("AddressableRouteComponent.Parent.Id is null"); + } + +#if FANTASY_DEVELOP + Log.Debug($"AddressableMessageComponent Register addressableId:{AddressableId} RouteId:{Parent.RuntimeId}"); +#endif + return AddressableHelper.AddAddressable(Scene, AddressableId, Parent.RuntimeId, isLock); + } + + /// + /// 锁定可寻址消息组件。 + /// + public FTask Lock() + { +#if FANTASY_DEVELOP + Log.Debug($"AddressableMessageComponent Lock {Parent.Id}"); +#endif + return AddressableHelper.LockAddressable(Scene, Parent.Id); + } + + /// + /// 解锁可寻址消息组件。 + /// + /// 解锁来源。 + public FTask UnLock(string source) + { +#if FANTASY_DEVELOP + Log.Debug($"AddressableMessageComponent UnLock {Parent.Id} {Parent.RuntimeId}"); +#endif + return AddressableHelper.UnLockAddressable(Scene, Parent.Id, Parent.RuntimeId, source); + } + + /// + /// 锁定可寻址消息并且释放掉AddressableMessageComponent组件。 + /// 该方法不会自动取Addressable中心删除自己的信息。 + /// 用于传送或转移到其他服务器时使用 + /// + public async FTask LockAndRelease() + { + await Lock(); + AddressableId = 0; + Dispose(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableMessageComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableMessageComponent.cs.meta new file mode 100644 index 00000000..6e5528be --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableMessageComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1eddf2d176eed4bba9f5cf8c3725318d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableRouteComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableRouteComponent.cs new file mode 100644 index 00000000..d7914a16 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableRouteComponent.cs @@ -0,0 +1,216 @@ +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Scheduler; +using Fantasy.Timer; + +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + public class AddressableRouteComponentAwakeSystem : AwakeSystem + { + protected override void Awake(AddressableRouteComponent self) + { + var selfScene = self.Scene; + self.TimerComponent = selfScene.TimerComponent; + self.NetworkMessagingComponent = selfScene.NetworkMessagingComponent; + self.MessageDispatcherComponent = selfScene.MessageDispatcherComponent; + self.AddressableRouteLock = + selfScene.CoroutineLockComponent.Create(self.GetType().TypeHandle.Value.ToInt64()); + } + } + + public class AddressableRouteComponentDestroySystem : DestroySystem + { + protected override void Destroy(AddressableRouteComponent self) + { + self.AddressableRouteLock.Dispose(); + + self.RouteId = 0; + self.AddressableId = 0; + self.TimerComponent = null; + self.AddressableRouteLock = null; + self.NetworkMessagingComponent = null; + self.MessageDispatcherComponent = null; + } + } + + /// + /// 可寻址路由消息组件,挂载了这个组件可以接收和发送 Addressable 消息。 + /// + public sealed class AddressableRouteComponent : Entity + { + public long RouteId; + public long AddressableId; + public CoroutineLock AddressableRouteLock; + public TimerComponent TimerComponent; + public NetworkMessagingComponent NetworkMessagingComponent; + public MessageDispatcherComponent MessageDispatcherComponent; + + internal void Send(IAddressableRouteMessage message) + { + Call(message).Coroutine(); + } + + internal async FTask Send(Type requestType, APackInfo packInfo) + { + await Call(requestType, packInfo); + } + + internal async FTask Call(Type requestType, APackInfo packInfo) + { + if (IsDisposed) + { + return MessageDispatcherComponent.CreateResponse(requestType, InnerErrorCode.ErrNotFoundRoute); + } + + packInfo.IsDisposed = true; + var failCount = 0; + var runtimeId = RuntimeId; + IResponse iRouteResponse = null; + + try + { + using (await AddressableRouteLock.Wait(AddressableId, "AddressableRouteComponent Call MemoryStream")) + { + while (!IsDisposed) + { + if (RouteId == 0) + { + RouteId = await AddressableHelper.GetAddressableRouteId(Scene, AddressableId); + } + + if (RouteId == 0) + { + return MessageDispatcherComponent.CreateResponse(requestType, + InnerErrorCode.ErrNotFoundRoute); + } + + iRouteResponse = await NetworkMessagingComponent.CallInnerRoute(RouteId, requestType, packInfo); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrRouteTimeout: + { + return iRouteResponse; + } + case InnerErrorCode.ErrNotFoundRoute: + { + if (++failCount > 20) + { + Log.Error($"AddressableComponent.Call failCount > 20 route send message fail, routeId: {RouteId} AddressableRouteComponent:{Id}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(100); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + RouteId = 0; + continue; + } + default: + { + return iRouteResponse; // 对于其他情况,直接返回响应,无需额外处理 + } + } + } + } + } + finally + { + packInfo.Dispose(); + } + + + return iRouteResponse; + } + + /// + /// 调用可寻址路由消息并等待响应。 + /// + /// 可寻址路由请求。 + private async FTask Call(IAddressableRouteMessage request) + { + if (IsDisposed) + { + return MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoute); + } + + var failCount = 0; + var runtimeId = RuntimeId; + + using (await AddressableRouteLock.Wait(AddressableId, "AddressableRouteComponent Call")) + { + while (true) + { + if (RouteId == 0) + { + RouteId = await AddressableHelper.GetAddressableRouteId(Scene, AddressableId); + } + + if (RouteId == 0) + { + return MessageDispatcherComponent.CreateResponse(request.GetType(), + InnerErrorCode.ErrNotFoundRoute); + } + + var iRouteResponse = await NetworkMessagingComponent.CallInnerRoute(RouteId, request); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrNotFoundRoute: + { + if (++failCount > 20) + { + Log.Error( + $"AddressableRouteComponent.Call failCount > 20 route send message fail, routeId: {RouteId} AddressableRouteComponent:{Id}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(500); + + if (runtimeId != RuntimeId) + { + iRouteResponse.ErrorCode = InnerErrorCode.ErrRouteTimeout; + } + + RouteId = 0; + continue; + } + case InnerErrorCode.ErrRouteTimeout: + { + return iRouteResponse; + } + default: + { + return iRouteResponse; + } + } + } + } + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableRouteComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableRouteComponent.cs.meta new file mode 100644 index 00000000..079e10fe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableRouteComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f0277349ccc64403aafb08a5b077c921 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableScene.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableScene.cs new file mode 100644 index 00000000..6abed4b5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableScene.cs @@ -0,0 +1,31 @@ +#if FANTASY_NET +using Fantasy.IdFactory; +using Fantasy.Platform.Net; + +namespace Fantasy.Network.Route +{ + /// + /// AddressableScene + /// + public sealed class AddressableScene + { + /// + /// Id + /// + public readonly long Id; + /// + /// RunTimeId + /// + public readonly long RunTimeId; + /// + /// 构造方法 + /// + /// sceneConfig + public AddressableScene(SceneConfig sceneConfig) + { + Id = new EntityIdStruct(0, sceneConfig.Id, (byte)sceneConfig.WorldConfigId, 0); + RunTimeId = new RuntimeIdStruct(0, sceneConfig.Id, (byte)sceneConfig.WorldConfigId, 0); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableScene.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableScene.cs.meta new file mode 100644 index 00000000..8e7a05b4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/AddressableScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 127ac839634c149d786e5e0a434f3535 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler.meta new file mode 100644 index 00000000..184f1cb2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b8a3fe1b1d90e4811b4a93dee5ec24bc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs new file mode 100644 index 00000000..847625b3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableAddHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableAddHandler : RouteRPC + { + /// + /// 在收到地址映射添加请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableAdd_Request 实例。 + /// 用于构建响应的 I_AddressableAdd_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableAdd_Request request, I_AddressableAdd_Response response, Action reply) + { + await scene.GetComponent().Add(request.AddressableId, request.RouteId, request.IsLock); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta new file mode 100644 index 00000000..8ced75a7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableAddHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46065fb3bfb094e599df0b688ed5774e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs new file mode 100644 index 00000000..f53c1f10 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableGetHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableGetHandler : RouteRPC + { + /// + /// 在收到地址映射获取请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableGet_Request 实例。 + /// 用于构建响应的 I_AddressableGet_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableGet_Request request, I_AddressableGet_Response response, Action reply) + { + response.RouteId = await scene.GetComponent().Get(request.AddressableId); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta new file mode 100644 index 00000000..4a926140 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableGetHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a56b75147cb624b488dcd13c47194864 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs new file mode 100644 index 00000000..b9642746 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableLockHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableLockHandler : RouteRPC + { + /// + /// 在收到地址映射锁定请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableLock_Request 实例。 + /// 用于构建响应的 I_AddressableLock_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableLock_Request request, I_AddressableLock_Response response, Action reply) + { + await scene.GetComponent().Lock(request.AddressableId); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta new file mode 100644 index 00000000..887c16f4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableLockHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b21a0f316703745ab94bb0379a8abd23 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs new file mode 100644 index 00000000..c4e96545 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs @@ -0,0 +1,26 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableRemoveHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableRemoveHandler : RouteRPC + { + /// + /// 在收到地址映射移除请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableRemove_Request 实例。 + /// 用于构建响应的 I_AddressableRemove_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableRemove_Request request, I_AddressableRemove_Response response, Action reply) + { + await scene.GetComponent().Remove(request.AddressableId); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta new file mode 100644 index 00000000..c7d830b6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableRemoveHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6204e4b7c87848cc8654d03e097ce2e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs new file mode 100644 index 00000000..1ab3937f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs @@ -0,0 +1,27 @@ +using Fantasy.Async; +using Fantasy.InnerMessage; +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network.Route +{ + /// + /// 声明一个 sealed 类 I_AddressableUnLockHandler,继承自 RouteRPC 类,并指定泛型参数 + /// + public sealed class I_AddressableUnLockHandler : RouteRPC + { + /// + /// 在收到地址映射解锁请求时执行的逻辑。 + /// + /// 当前场景实例。 + /// 包含请求信息的 I_AddressableUnLock_Request 实例。 + /// 用于构建响应的 I_AddressableUnLock_Response 实例。 + /// 执行响应的回调操作。 + protected override async FTask Run(Scene scene, I_AddressableUnLock_Request request, I_AddressableUnLock_Response response, Action reply) + { + scene.GetComponent().UnLock(request.AddressableId, request.RouteId, request.Source); + await FTask.CompletedTask; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta new file mode 100644 index 00000000..b156c142 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Addressable/Handler/I_AddressableUnLockHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c95afece21cd04b708b4c29e2f639d9a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/MemoryStreamBufferPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/MemoryStreamBufferPool.cs new file mode 100644 index 00000000..6e6d4f7a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/MemoryStreamBufferPool.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using Fantasy.Serialize; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Network +{ + /// + /// MemoryStreamBuffer对象池类 + /// + public sealed class MemoryStreamBufferPool : IDisposable + { + private readonly int _poolSize; + private readonly int _maxMemoryStreamSize; + private readonly Queue _memoryStreamPool = new Queue(); + + /// + /// 构造方法 + /// + /// + /// + public MemoryStreamBufferPool(int maxMemoryStreamSize = 2048, int poolSize = 512) + { + _poolSize = poolSize; + _maxMemoryStreamSize = maxMemoryStreamSize; + } + + /// + /// 租借MemoryStream + /// + /// + /// + /// + public MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + if (size > _maxMemoryStreamSize) + { + return new MemoryStreamBuffer(memoryStreamBufferSource, size); + } + + if (size < _maxMemoryStreamSize) + { + size = _maxMemoryStreamSize; + } + + if (_memoryStreamPool.Count == 0) + { + return new MemoryStreamBuffer(memoryStreamBufferSource, size); + } + + if (_memoryStreamPool.TryDequeue(out var memoryStream)) + { + memoryStream.MemoryStreamBufferSource = memoryStreamBufferSource; + return memoryStream; + } + + return new MemoryStreamBuffer(memoryStreamBufferSource, size); + } + + /// + /// 归还ReturnMemoryStream + /// + /// + public void ReturnMemoryStream(MemoryStreamBuffer memoryStreamBuffer) + { + if (memoryStreamBuffer.Capacity > _maxMemoryStreamSize) + { + return; + } + + if (_memoryStreamPool.Count > _poolSize) + { + // 设置该值只能是内网或服务器转发的时候可能在连接之前发送的数据过多的情况下可以修改。 + // 设置过大会导致内存占用过大,所以要谨慎设置。 + return; + } + + memoryStreamBuffer.SetLength(0); + memoryStreamBuffer.MemoryStreamBufferSource = MemoryStreamBufferSource.None; + _memoryStreamPool.Enqueue(memoryStreamBuffer); + } + + /// + /// 销毁方法 + /// + public void Dispose() + { + foreach (var memoryStreamBuffer in _memoryStreamPool) + { + memoryStreamBuffer.MemoryStreamBufferSource = MemoryStreamBufferSource.None; + memoryStreamBuffer.Dispose(); + } + _memoryStreamPool.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/MemoryStreamBufferPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/MemoryStreamBufferPool.cs.meta new file mode 100644 index 00000000..183c9e14 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/MemoryStreamBufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f24c32bf558c48ff8e21e4915589cfd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message.meta new file mode 100644 index 00000000..ba20ecff --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2f8b2faba89c949528b8639b2b6f3aae +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher.meta new file mode 100644 index 00000000..6e3bd77c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d5aa2194ae17943c2bdef0980223e18e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface.meta new file mode 100644 index 00000000..ab43ba49 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d4d6dc6851edd49279319bb39e3ee406 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs new file mode 100644 index 00000000..0febb3a9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs @@ -0,0 +1,221 @@ +// ReSharper disable InconsistentNaming + +using System; +using System.Collections.Generic; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Network; +using Fantasy.Serialize; + +namespace Fantasy.Network.Interface +{ + /// + /// 表示消息处理器的接口,处理特定类型的消息。 + /// + public interface IMessageHandler + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type(); + /// + /// 处理消息的方法。 + /// + /// 会话对象。 + /// RPC标识。 + /// 消息类型代码。 + /// 要处理的消息。 + /// 异步任务。 + UniTask Handle(Session session, uint rpcId, uint messageTypeCode, object message); + } + + /// + /// 泛型消息基类,实现了 接口。 + /// + public abstract class Message : IMessageHandler + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(T); + } + + /// + /// 处理消息的方法。 + /// + /// 会话对象。 + /// RPC标识。 + /// 消息类型代码。 + /// 要处理的消息。 + /// 异步任务。 + public async UniTask Handle(Session session, uint rpcId, uint messageTypeCode, object message) + { + try + { + await Run(session, (T) message); + } + catch (Exception e) + { + Log.Error(e); + } + } + + /// + /// 运行消息处理逻辑。 + /// + /// 会话对象。 + /// 要处理的消息。 + /// 异步任务。 + protected abstract UniTask Run(Session session, T message); + } + + /// + /// 泛型消息RPC基类,实现了 接口,用于处理请求和响应类型的消息。 + /// + public abstract class MessageRPC : IMessageHandler where TRequest : IRequest where TResponse : AMessage, IResponse, new() + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRequest); + } + + /// + /// 处理消息的方法。 + /// + /// 会话对象。 + /// RPC标识。 + /// 消息类型代码。 + /// 要处理的消息。 + /// 异步任务。 + public async UniTask Handle(Session session, uint rpcId, uint messageTypeCode, object message) + { + if (message is not TRequest request) + { + Log.Error($"消息类型转换错误: {message.GetType().Name} to {typeof(TRequest).Name}"); + return; + } + + var response = new TResponse(); + var isReply = false; + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(session, request, response, Reply); + } + catch (Exception e) + { + Log.Error(e); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行消息处理逻辑。 + /// + /// 会话对象。 + /// 请求消息。 + /// 响应消息。 + /// 发送响应的方法。 + /// 异步任务。 + protected abstract UniTask Run(Session session, TRequest request, TResponse response, Action reply); + } +#if FANTASY_UNITY + public interface IMessageDelegateHandler + { + /// + /// 注册消息处理器。 + /// + /// + public void Register(object @delegate); + /// + /// 取消注册消息处理器。 + /// + /// + public int UnRegister(object @delegate); + /// + /// 处理消息的方法。 + /// + /// + /// + public void Handle(Session session, object message); + } + public delegate UniTask MessageDelegate(Session session, T msg) where T : IMessage; + public sealed class MessageDelegateHandler : IMessageDelegateHandler, IDisposable where T : IMessage + { + private readonly List> _delegates = new List>(); + + public Type Type() + { + return typeof(T); + } + + public void Register(object @delegate) + { + var a = (MessageDelegate)@delegate; + + if (_delegates.Contains(a)) + { + Log.Error($"{typeof(T).Name} already register action delegateName:{a.Method.Name}"); + return; + } + + _delegates.Add(a); + } + + public int UnRegister(object @delegate) + { + _delegates.Remove((MessageDelegate)@delegate); + return _delegates.Count; + } + + public void Handle(Session session, object message) + { + foreach (var registerDelegate in _delegates) + { + try + { + registerDelegate(session, (T)message).Forget(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public void Dispose() + { + _delegates.Clear(); + } + } +#endif +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta new file mode 100644 index 00000000..df81f048 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IMessageHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8d500d1bea9d477dac23323bd387d47 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs new file mode 100644 index 00000000..f027aec6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs @@ -0,0 +1,338 @@ +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.InnerMessage; +using Fantasy.Network; +using Fantasy.Serialize; + +#if FANTASY_NET +// ReSharper disable InconsistentNaming + +namespace Fantasy.Network.Interface +{ + /// + /// 表示路由消息处理器的接口,处理特定类型的路由消息。 + /// + public interface IRouteMessageHandler + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type(); + + /// + /// 处理路由消息的方法。 + /// + /// 会话对象。 + /// 实体对象。 + /// RPC标识。 + /// 要处理的路由消息。 + /// 异步任务。 + FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage); + } + + /// + /// 泛型路由基类,实现了 接口,用于处理特定实体和路由消息类型的路由。 + /// + /// 实体类型。 + /// 路由消息类型。 + public abstract class Route : IRouteMessageHandler where TEntity : Entity where TMessage : IRouteMessage + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TMessage); + } + + /// + /// 处理路由消息的方法。 + /// + /// 会话对象。 + /// 实体对象。 + /// RPC标识。 + /// 要处理的路由消息。 + /// 异步任务。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TMessage ruteMessage) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TMessage).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"Route type conversion error: {entity.GetType().Name} to {nameof(TEntity)}"); + return; + } + + try + { + await Run(tEntity, ruteMessage); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + } + } + + /// + /// 运行路由消息处理逻辑。 + /// + /// 实体对象。 + /// 要处理的路由消息。 + /// 异步任务。 + protected abstract FTask Run(TEntity entity, TMessage message); + } + + /// + /// 泛型路由RPC基类,实现了 接口,用于处理请求和响应类型的路由。 + /// + /// 实体类型。 + /// 路由请求类型。 + /// 路由响应类型。 + public abstract class RouteRPC : IRouteMessageHandler where TEntity : Entity where TRouteRequest : IRouteRequest where TRouteResponse : AMessage, IRouteResponse, new() + { + /// + /// 获取处理的消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRouteRequest); + } + + /// + /// 处理路由消息的方法。 + /// + /// 会话对象。 + /// 实体对象。 + /// RPC标识。 + /// 要处理的路由消息。 + /// 异步任务。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TRouteRequest tRouteRequest) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TRouteRequest).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"Route type conversion error: {entity.GetType().Name} to {nameof(TEntity)}"); + return; + } + + var isReply = false; + var response = new TRouteResponse(); + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(tEntity, tRouteRequest, response, Reply); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行路由消息处理逻辑。 + /// + /// 实体对象。 + /// 请求路由消息。 + /// 响应路由消息。 + /// 发送响应的方法。 + /// 异步任务。 + protected abstract FTask Run(TEntity entity, TRouteRequest request, TRouteResponse response, Action reply); + } + + /// + /// 泛型可寻址路由基类,实现了 接口,用于处理特定实体和可寻址路由消息类型的路由。 + /// + /// 实体类型。 + /// 可寻址路由消息类型。 + public abstract class Addressable : IRouteMessageHandler where TEntity : Entity where TMessage : IAddressableRouteMessage + { + /// + /// 获取消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TMessage); + } + + /// + /// 处理可寻址路由消息。 + /// + /// 会话。 + /// 实体。 + /// RPC标识。 + /// 可寻址路由消息。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TMessage ruteMessage) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TMessage).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"Route type conversion error: {entity.GetType().Name} to {nameof(TEntity)}"); + return; + } + + try + { + await Run(tEntity, ruteMessage); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + } + finally + { + session.Send(new RouteResponse(), rpcId); + } + } + + /// + /// 运行处理可寻址路由消息。 + /// + /// 实体。 + /// 可寻址路由消息。 + protected abstract FTask Run(TEntity entity, TMessage message); + } + + /// + /// 泛型可寻址RPC路由基类,实现了 接口,用于处理特定实体和可寻址RPC路由请求类型的路由。 + /// + /// 实体类型。 + /// 可寻址RPC路由请求类型。 + /// 可寻址RPC路由响应类型。 + public abstract class AddressableRPC : IRouteMessageHandler where TEntity : Entity where TRouteRequest : IAddressableRouteRequest where TRouteResponse : IAddressableRouteResponse, new() + { + /// + /// 获取消息类型。 + /// + /// 消息类型。 + public Type Type() + { + return typeof(TRouteRequest); + } + + /// + /// 处理可寻址RPC路由请求。 + /// + /// 会话。 + /// 实体。 + /// RPC标识。 + /// 可寻址RPC路由请求。 + public async FTask Handle(Session session, Entity entity, uint rpcId, object routeMessage) + { + if (routeMessage is not TRouteRequest tRouteRequest) + { + Log.Error($"Message type conversion error: {routeMessage.GetType().FullName} to {typeof(TRouteRequest).Name}"); + return; + } + + if (entity is not TEntity tEntity) + { + Log.Error($"Route type conversion error: {entity.GetType().Name} to {nameof(TEntity)}"); + return; + } + + var isReply = false; + var response = new TRouteResponse(); + + void Reply() + { + if (isReply) + { + return; + } + + isReply = true; + + if (session.IsDisposed) + { + return; + } + + session.Send(response, rpcId); + } + + try + { + await Run(tEntity, tRouteRequest, response, Reply); + } + catch (Exception e) + { + if (entity is not Scene scene) + { + scene = entity.Scene; + } + + Log.Error($"SceneConfigId:{session.Scene.SceneConfigId} ProcessConfigId:{scene.Process.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}"); + response.ErrorCode = InnerErrorCode.ErrRpcFail; + } + finally + { + Reply(); + } + } + + /// + /// 运行处理可寻址RPC路由请求。 + /// + /// 实体。 + /// 可寻址RPC路由请求。 + /// 可寻址RPC路由响应。 + /// 回复操作。 + protected abstract FTask Run(TEntity entity, TRouteRequest request, TRouteResponse response, Action reply); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta new file mode 100644 index 00000000..c019cad4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/Interface/IRouteMessageHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1d2e3f63e08dc406c858a416337569f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs new file mode 100644 index 00000000..cbab84eb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs @@ -0,0 +1,428 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Cysharp.Threading.Tasks; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.DataStructure.Dictionary; +using Fantasy.Entitas; +using Fantasy.InnerMessage; +using Fantasy.Network; + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.Interface +{ + /// + /// 用于存储消息处理器的信息,包括类型和对象实例。 + /// + /// 消息处理器的类型 + internal sealed class HandlerInfo + { + /// + /// 获取或设置消息处理器对象。 + /// + public T Obj; + /// + /// 获取或设置消息处理器的类型。 + /// + public Type Type; + } + + /// + /// 网络消息分发组件。 + /// + public sealed class MessageDispatcherComponent : Entity, IAssembly + { + public long AssemblyIdentity { get; set; } + private readonly Dictionary _responseTypes = new Dictionary(); + private readonly DoubleMapDictionary _networkProtocols = new DoubleMapDictionary(); + private readonly Dictionary _messageHandlers = new Dictionary(); + private readonly OneToManyList _assemblyResponseTypes = new OneToManyList(); + private readonly OneToManyList _assemblyNetworkProtocols = new OneToManyList(); + private readonly OneToManyList> _assemblyMessageHandlers = new OneToManyList>(); +#if FANTASY_UNITY + + private readonly Dictionary _messageDelegateHandlers = new Dictionary(); +#endif +#if FANTASY_NET + private readonly Dictionary _customRouteMap = new Dictionary(); + private readonly OneToManyList _assemblyCustomRouteMap = new OneToManyList(); + private readonly Dictionary _routeMessageHandlers = new Dictionary(); + private readonly OneToManyList> _assemblyRouteMessageHandlers = new OneToManyList>(); +#endif + private CoroutineLock _receiveRouteMessageLock; + + #region Initialize + + internal async UniTask Initialize() + { + _receiveRouteMessageLock = Scene.CoroutineLockComponent.Create(GetType().TypeHandle.Value.ToInt64()); + await AssemblySystem.Register(this); + return this; + } + + public async UniTask Load(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + LoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + await tcs.Task; + } + + private void LoadInner(long assemblyIdentity) + { + // 遍历所有实现了IMessage接口的类型,获取OpCode并添加到_networkProtocols字典中 + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IMessage))) + { + var obj = (IMessage) Activator.CreateInstance(type); + var opCode = obj.OpCode(); + + _networkProtocols.Add(opCode, type); + + var responseType = type.GetProperty("ResponseType"); + + // 如果类型具有ResponseType属性,将其添加到_responseTypes字典中 + if (responseType != null) + { + _responseTypes.Add(type, responseType.PropertyType); + _assemblyResponseTypes.Add(assemblyIdentity, type); + } + + _assemblyNetworkProtocols.Add(assemblyIdentity, opCode); + } + + // 遍历所有实现了IMessageHandler接口的类型,创建实例并添加到_messageHandlers字典中 + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IMessageHandler))) + { + var obj = (IMessageHandler) Activator.CreateInstance(type); + + if (obj == null) + { + throw new Exception($"message handle {type.Name} is null"); + } + + var key = obj.Type(); + _messageHandlers.Add(key, obj); + _assemblyMessageHandlers.Add(assemblyIdentity, new HandlerInfo() + { + Obj = obj, Type = key + }); + } + + // 如果编译符号FANTASY_NET存在,遍历所有实现了IRouteMessageHandler接口的类型,创建实例并添加到_routeMessageHandlers字典中 +#if FANTASY_NET + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(IRouteMessageHandler))) + { + var obj = (IRouteMessageHandler) Activator.CreateInstance(type); + + if (obj == null) + { + throw new Exception($"message handle {type.Name} is null"); + } + + var key = obj.Type(); + _routeMessageHandlers.Add(key, obj); + _assemblyRouteMessageHandlers.Add(assemblyIdentity, new HandlerInfo() + { + Obj = obj, Type = key + }); + } + + foreach (var type in AssemblySystem.ForEach(assemblyIdentity, typeof(ICustomRoute))) + { + var obj = (ICustomRoute) Activator.CreateInstance(type); + + if (obj == null) + { + throw new Exception($"message handle {type.Name} is null"); + } + + var opCode = obj.OpCode(); + _customRouteMap[opCode] = obj.RouteType; + _assemblyCustomRouteMap.Add(assemblyIdentity, opCode); + } +#endif + } + + public async UniTask ReLoad(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + LoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + await tcs.Task; + } + + public async UniTask OnUnLoad(long assemblyIdentity) + { + var tcs = AutoResetUniTaskCompletionSourcePlus.Create(); + Scene.ThreadSynchronizationContext.Post(() => + { + OnUnLoadInner(assemblyIdentity); + tcs.TrySetResult(); + }); + await tcs.Task; + } + + private void OnUnLoadInner(long assemblyIdentity) + { + // 移除程序集对应的ResponseType类型和OpCode信息 + if (_assemblyResponseTypes.TryGetValue(assemblyIdentity, out var removeResponseTypes)) + { + foreach (var removeResponseType in removeResponseTypes) + { + _responseTypes.Remove(removeResponseType); + } + + _assemblyResponseTypes.RemoveByKey(assemblyIdentity); + } + + if (_assemblyNetworkProtocols.TryGetValue(assemblyIdentity, out var removeNetworkProtocols)) + { + foreach (var removeNetworkProtocol in removeNetworkProtocols) + { + _networkProtocols.RemoveByKey(removeNetworkProtocol); + } + + _assemblyNetworkProtocols.RemoveByKey(assemblyIdentity); + } + + // 移除程序集对应的消息处理器信息 + if (_assemblyMessageHandlers.TryGetValue(assemblyIdentity, out var removeMessageHandlers)) + { + foreach (var removeMessageHandler in removeMessageHandlers) + { + _messageHandlers.Remove(removeMessageHandler.Type); + } + + _assemblyMessageHandlers.RemoveByKey(assemblyIdentity); + } + + // 如果编译符号FANTASY_NET存在,移除程序集对应的路由消息处理器信息 +#if FANTASY_NET + if (_assemblyRouteMessageHandlers.TryGetValue(assemblyIdentity, out var removeRouteMessageHandlers)) + { + foreach (var removeRouteMessageHandler in removeRouteMessageHandlers) + { + _routeMessageHandlers.Remove(removeRouteMessageHandler.Type); + } + + _assemblyRouteMessageHandlers.RemoveByKey(assemblyIdentity); + } + + if (_assemblyCustomRouteMap.TryGetValue(assemblyIdentity, out var removeCustomRouteMap)) + { + foreach (var removeCustom in removeCustomRouteMap) + { + _customRouteMap.Remove(removeCustom); + } + + _assemblyCustomRouteMap.RemoveByKey(assemblyIdentity); + } +#endif + } + +#if FANTASY_UNITY + /// + /// 手动注册一个消息处理器。 + /// + /// + /// + public void RegisterHandler(MessageDelegate @delegate) where T : IMessage + { + var type = typeof(T); + + if (!_messageDelegateHandlers.TryGetValue(type, out var messageDelegate)) + { + messageDelegate = new MessageDelegateHandler(); + _messageDelegateHandlers.Add(type,messageDelegate); + } + + messageDelegate.Register(@delegate); + } + + /// + /// 手动卸载一个消息处理器,必须是通过RegisterHandler方法注册的消息处理器。 + /// + /// + /// + public void UnRegisterHandler(MessageDelegate @delegate) where T : IMessage + { + var type = typeof(T); + + if (!_messageDelegateHandlers.TryGetValue(type, out var messageDelegate)) + { + return; + } + + if (messageDelegate.UnRegister(@delegate) != 0) + { + return; + } + + _messageDelegateHandlers.Remove(type); + } +#endif + + #endregion + + /// + /// 处理普通消息,将消息分发给相应的消息处理器。 + /// + /// 会话对象 + /// 消息类型 + /// 消息对象 + /// RPC标识 + /// 协议码 + public void MessageHandler(Session session, Type type, object message, uint rpcId, uint protocolCode) + { +#if FANTASY_UNITY + if(_messageDelegateHandlers.TryGetValue(type,out var messageDelegateHandler)) + { + messageDelegateHandler.Handle(session, message); + return; + } +#endif + if (!_messageHandlers.TryGetValue(type, out var messageHandler)) + { + Log.Warning($"Scene:{session.Scene.Id} Found Unhandled Message: {message.GetType()}"); + return; + } + + // 调用消息处理器的Handle方法并启动协程执行处理逻辑 + messageHandler.Handle(session, rpcId, protocolCode, message).Forget(); + } + + // 如果编译符号FANTASY_NET存在,定义处理路由消息的方法 +#if FANTASY_NET + /// + /// 处理路由消息,将消息分发给相应的路由消息处理器。 + /// + /// 会话对象 + /// 消息类型 + /// 实体对象 + /// 消息对象 + /// RPC标识 + public async FTask RouteMessageHandler(Session session, Type type, Entity entity, object message, uint rpcId) + { + if (!_routeMessageHandlers.TryGetValue(type, out var routeMessageHandler)) + { + Log.Warning($"Scene:{session.Scene.Id} Found Unhandled RouteMessage: {message.GetType()}"); + + if (message is IRouteRequest request) + { + FailRouteResponse(session, request.GetType(), InnerErrorCode.ErrEntityNotFound, rpcId); + } + + return; + } + + var runtimeId = entity.RuntimeId; + var sessionRuntimeId = session.RuntimeId; + + if (entity is Scene) + { + // 如果是Scene的话、就不要加锁了、如果加锁很一不小心就可能会造成死锁 + await routeMessageHandler.Handle(session, entity, rpcId, message); + return; + } + + // 使用协程锁来确保多线程安全 + using (await _receiveRouteMessageLock.Wait(runtimeId)) + { + if (sessionRuntimeId != session.RuntimeId) + { + return; + } + + if (runtimeId != entity.RuntimeId) + { + if (message is IRouteRequest request) + { + FailRouteResponse(session, request.GetType(), InnerErrorCode.ErrEntityNotFound, rpcId); + } + + return; + } + + await routeMessageHandler.Handle(session, entity, rpcId, message); + } + } + + internal bool GetCustomRouteType(long protocolCode,out int routeType) + { + return _customRouteMap.TryGetValue(protocolCode, out routeType); + } +#endif + internal void FailRouteResponse(Session session, Type requestType, uint error, uint rpcId) + { + var response = CreateRouteResponse(requestType, error); + session.Send(response, rpcId); + } + + internal IResponse CreateResponse(Type requestType, uint error) + { + IResponse response; + + if (_responseTypes.TryGetValue(requestType, out var responseType)) + { + response = (IResponse) Activator.CreateInstance(responseType); + } + else + { + response = new Response(); + } + + response.ErrorCode = error; + return response; + } + + internal IRouteResponse CreateRouteResponse(Type requestType, uint error) + { + IRouteResponse response; + + if (_responseTypes.TryGetValue(requestType, out var responseType)) + { + response = (IRouteResponse) Activator.CreateInstance(responseType); + } + else + { + response = new RouteResponse(); + } + + response.ErrorCode = error; + return response; + } + + /// + /// 根据消息类型获取对应的OpCode。 + /// + /// 消息类型 + /// 消息对应的OpCode + public uint GetOpCode(Type type) + { + return _networkProtocols.GetKeyByValue(type); + } + + /// + /// 根据OpCode获取对应的消息类型。 + /// + /// OpCode + /// OpCode对应的消息类型 + public Type GetOpCodeType(uint code) + { + return _networkProtocols.GetValueByKey(code); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta new file mode 100644 index 00000000..2979d9d7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Dispatcher/MessageDispatcherComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 56299d59c80c145b4b680252e4fd4202 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/IMessage.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/IMessage.cs new file mode 100644 index 00000000..704b7360 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/IMessage.cs @@ -0,0 +1,83 @@ +using System; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + /// + /// 表示通用消息接口。 + /// + public interface IMessage + { + /// + /// 获取消息的操作代码。 + /// + /// 操作代码。 + uint OpCode(); + } + + /// + /// 表示请求消息接口。 + /// + public interface IRequest : IMessage + { + + } + + /// + /// 表示响应消息接口。 + /// + public interface IResponse : IMessage + { + /// + /// 获取或设置错误代码。 + /// + uint ErrorCode { get; set; } + } + // 普通路由消息 + /// + /// 表示普通路由消息的接口,继承自请求接口。 + /// + public interface IRouteMessage : IRequest + { + + } + + /// + /// 普通路由请求接口,继承自普通路由消息接口。 + /// + public interface IRouteRequest : IRouteMessage { } + /// + /// 普通路由响应接口,继承自响应接口。 + /// + public interface IRouteResponse : IResponse { } + // 可寻址协议 + /// + /// 表示可寻址协议的普通路由消息接口,继承自普通路由消息接口。 + /// + public interface IAddressableRouteMessage : IRouteMessage { } + /// + /// 可寻址协议的普通路由请求接口,继承自可寻址协议的普通路由消息接口。 + /// + public interface IAddressableRouteRequest : IRouteRequest { } + /// + /// 可寻址协议的普通路由响应接口,继承自普通路由响应接口。 + /// + public interface IAddressableRouteResponse : IRouteResponse { } + // 自定义Route协议 + public interface ICustomRoute : IMessage + { + int RouteType { get; } + } + /// + /// 表示自定义Route协议的普通路由消息接口,继承自普通路由消息接口。 + /// + public interface ICustomRouteMessage : IRouteMessage, ICustomRoute { } + /// + /// 自定义Route协议的普通路由请求接口,继承自自定义Route协议的普通路由消息接口。 + /// + public interface ICustomRouteRequest : IRouteRequest, ICustomRoute { } + /// + /// 自定义Route协议的普通路由响应接口,继承自普通路由响应接口。 + /// + public interface ICustomRouteResponse : IRouteResponse { } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/IMessage.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/IMessage.cs.meta new file mode 100644 index 00000000..7b9f6c61 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/IMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 601b2373608f44b0eb7d4a6f8aa44ea5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/InnerMessage.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/InnerMessage.cs new file mode 100644 index 00000000..8910a34e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/InnerMessage.cs @@ -0,0 +1,209 @@ +using Fantasy.Network.Interface; +using Fantasy.Serialize; +using ProtoBuf; + +// ReSharper disable InconsistentNaming +// ReSharper disable PropertyCanBeMadeInitOnly.Global +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.InnerMessage +{ + [ProtoContract] + public sealed partial class BenchmarkMessage : AMessage, IMessage + { + public uint OpCode() + { + return Fantasy.Network.OpCode.BenchmarkMessage; + } + } + [ProtoContract] + public partial class BenchmarkRequest : AMessage, IRequest + { + public uint OpCode() + { + return Fantasy.Network.OpCode.BenchmarkRequest; + } + [ProtoIgnore] + public BenchmarkResponse ResponseType { get; set; } + [ProtoMember(1)] + public long RpcId { get; set; } + } + + [ProtoContract] + public partial class BenchmarkResponse : AMessage, IResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.BenchmarkResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + public sealed partial class Response : AMessage, IResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.DefaultResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public sealed partial class RouteResponse : AMessage, IRouteResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.DefaultRouteResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class PingRequest : AMessage, IRequest + { + public uint OpCode() + { + return Fantasy.Network.OpCode.PingRequest; + } + [ProtoIgnore] + public PingResponse ResponseType { get; set; } + [ProtoMember(1)] + public long RpcId { get; set; } + } + + [ProtoContract] + public partial class PingResponse : AMessage, IResponse + { + public uint OpCode() + { + return Fantasy.Network.OpCode.PingResponse; + } + [ProtoMember(1)] + public long RpcId { get; set; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + [ProtoMember(3)] + public long Now; + } + [ProtoContract] + public partial class I_AddressableAdd_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableAdd_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableAddRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + [ProtoMember(2)] + public long RouteId { get; set; } + [ProtoMember(3)] + public bool IsLock { get; set; } + } + [ProtoContract] + public partial class I_AddressableAdd_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableAddResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_AddressableGet_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableGet_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableGetRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + } + [ProtoContract] + public partial class I_AddressableGet_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableGetResponse; } + [ProtoMember(2)] + public uint ErrorCode { get; set; } + [ProtoMember(1)] + public long RouteId { get; set; } + } + [ProtoContract] + public partial class I_AddressableRemove_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableRemove_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableRemoveRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + } + [ProtoContract] + public partial class I_AddressableRemove_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableRemoveResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_AddressableLock_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableLock_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableLockRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + } + [ProtoContract] + public partial class I_AddressableLock_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableLockResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class I_AddressableUnLock_Request : AMessage, IRouteRequest + { + [ProtoIgnore] + public I_AddressableUnLock_Response ResponseType { get; set; } + public uint OpCode() { return Fantasy.Network.OpCode.AddressableUnLockRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public long AddressableId { get; set; } + [ProtoMember(2)] + public long RouteId { get; set; } + [ProtoMember(3)] + public string Source { get; set; } + } + [ProtoContract] + public partial class I_AddressableUnLock_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.AddressableUnLockResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } + [ProtoContract] + public partial class LinkEntity_Request : AMessage, IRouteRequest + { + public uint OpCode() { return Fantasy.Network.OpCode.LinkEntityRequest; } + public long RouteTypeOpCode() { return 1; } + [ProtoMember(1)] + public int EntityType { get; set; } + [ProtoMember(2)] + public long RuntimeId { get; set; } + [ProtoMember(3)] + public long LinkGateSessionRuntimeId { get; set; } + } + [ProtoContract] + public partial class LinkEntity_Response : AMessage, IRouteResponse + { + public uint OpCode() { return Fantasy.Network.OpCode.LinkEntityResponse; } + [ProtoMember(1)] + public uint ErrorCode { get; set; } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/InnerMessage.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/InnerMessage.cs.meta new file mode 100644 index 00000000..4806975c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/InnerMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15efa930197b84bbf90cfc342ffe33e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser.meta new file mode 100644 index 00000000..4defc493 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 56103a3dd3e924bdd9505d769cb1cc88 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler.meta new file mode 100644 index 00000000..e2bb99df --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e0bcbd023c1f442f9b96be44fd32441a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs new file mode 100644 index 00000000..e4d1540f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs @@ -0,0 +1,386 @@ +using System; +using System.Buffers; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.PacketParser +{ + /// + /// BufferPacketParser消息格式化器抽象类 + /// 这个不会用在TCP协议中、因此不用考虑分包和粘包的问题。 + /// 目前这个只会用在KCP协议中、因为KCP出来的就是一个完整的包、所以可以一次性全部解析出来。 + /// 如果是用在其他协议上可能会出现问题。 + /// + public abstract class BufferPacketParser : APacketParser + { + protected uint RpcId; + protected long RouteId; + protected uint ProtocolCode; + protected int MessagePacketLength; + public override void Dispose() + { + RpcId = 0; + RouteId = 0; + ProtocolCode = 0; + MessagePacketLength = 0; + base.Dispose(); + } + /// + /// 解包方法 + /// + /// buffer + /// count + /// packInfo + /// + public abstract bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo); + } +#if FANTASY_NET + /// + /// 服务器之间专用的BufferPacketParser消息格式化器 + /// + public sealed class InnerBufferPacketParser : BufferPacketParser + { + /// + /// + /// + /// + /// + /// + /// + /// + public override unsafe bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo) + { + packInfo = null; + + if (buffer.Length < count) + { + throw new ScanException($"The buffer length is less than the specified count. buffer.Length={buffer.Length} count={count}"); + } + + if (count < Packet.InnerPacketHeadLength) + { + // 如果内存资源中的数据长度小于内部消息头的长度,无法解析 + return false; + } + + fixed (byte* bufferPtr = buffer) + { + MessagePacketLength = *(int*)bufferPtr; + + if (MessagePacketLength > Packet.PacketBodyMaxLength || count < MessagePacketLength) + { + // 检查消息体长度是否超出限制 + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + ProtocolCode = *(uint*)(bufferPtr + Packet.PacketLength); + RpcId = *(uint*)(bufferPtr + Packet.InnerPacketRpcIdLocation); + RouteId = *(long*)(bufferPtr + Packet.InnerPacketRouteRouteIdLocation); + } + + packInfo = InnerPackInfo.Create(Network); + packInfo.RpcId = RpcId; + packInfo.RouteId = RouteId; + packInfo.ProtocolCode = ProtocolCode; + packInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, count).Write(buffer, 0, count); + return true; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, ref routeId, message) : Pack(ref rpcId, ref routeId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream) + { + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(uint*)(bufferPtr + Packet.InnerPacketRpcIdLocation) = rpcId; + *(long*)(bufferPtr + Packet.InnerPacketRouteRouteIdLocation) = routeId; + } + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.InnerPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(int*)bufferPtr = packetBodyCount; + *(uint*)(bufferPtr + Packet.PacketLength) = opCode; + *(uint*)(bufferPtr + Packet.InnerPacketRpcIdLocation) = rpcId; + *(long*)(bufferPtr + Packet.InnerPacketRouteRouteIdLocation) = routeId; + } + + return memoryStream; + } + } +#endif + /// + /// 客户端和服务器之间专用的BufferPacketParser消息格式化器 + /// + public sealed class OuterBufferPacketParser : BufferPacketParser + { + /// + /// + /// + /// + /// + /// + /// + /// + public override unsafe bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo) + { + packInfo = null; + + if (buffer.Length < count) + { + throw new ScanException($"The buffer length is less than the specified count. buffer.Length={buffer.Length} count={count}"); + } + + if (count < Packet.OuterPacketHeadLength) + { + // 如果内存资源中的数据长度小于内部消息头的长度,无法解析 + return false; + } + + fixed (byte* bufferPtr = buffer) + { + MessagePacketLength = *(int*)bufferPtr; + + if (MessagePacketLength > Packet.PacketBodyMaxLength || count < MessagePacketLength) + { + // 检查消息体长度是否超出限制 + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + ProtocolCode = *(uint*)(bufferPtr + Packet.PacketLength); + RpcId = *(uint*)(bufferPtr + Packet.OuterPacketRpcIdLocation); + } + + packInfo = OuterPackInfo.Create(Network); + packInfo.RpcId = RpcId; + packInfo.ProtocolCode = ProtocolCode; + packInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, count).Write(buffer, 0, count); + return true; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, message) : Pack(ref rpcId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, MemoryStreamBuffer memoryStream) + { + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(uint*)(bufferPtr + Packet.InnerPacketRpcIdLocation) = rpcId; + } + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(int*)bufferPtr = packetBodyCount; + *(uint*)(bufferPtr + Packet.PacketLength) = opCode; + *(uint*)(bufferPtr + Packet.OuterPacketRpcIdLocation) = rpcId; + } + + return memoryStream; + } + } + /// + /// Webgl专用的客户端和服务器之间专用的BufferPacketParser消息格式化器 + /// + public sealed class OuterWebglBufferPacketParser : BufferPacketParser + { + /// + /// + /// + /// + /// + /// + /// + /// + public override bool UnPack(byte[] buffer, ref int count, out APackInfo packInfo) + { + packInfo = null; + + if (buffer.Length < count) + { + throw new ScanException($"The buffer length is less than the specified count. buffer.Length={buffer.Length} count={count}"); + } + + if (count < Packet.OuterPacketHeadLength) + { + // 如果内存资源中的数据长度小于内部消息头的长度,无法解析 + return false; + } + + MessagePacketLength = BitConverter.ToInt32(buffer, 0); + + if (MessagePacketLength > Packet.PacketBodyMaxLength || count < MessagePacketLength) + { + // 检查消息体长度是否超出限制 + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + ProtocolCode = BitConverter.ToUInt32(buffer, Packet.PacketLength); + RpcId = BitConverter.ToUInt32(buffer, Packet.OuterPacketRpcIdLocation); + + packInfo = OuterPackInfo.Create(Network); + packInfo.RpcId = RpcId; + packInfo.ProtocolCode = ProtocolCode; + packInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, count).Write(buffer, 0, count); + return true; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, message) : Pack(ref rpcId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, MemoryStreamBuffer memoryStream) + { + var buffer = memoryStream.GetBuffer().AsSpan(); +#if FANTASY_NET + MemoryMarshal.Write(buffer.Slice(Packet.OuterPacketRpcIdLocation, sizeof(uint)), in rpcId); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(buffer.Slice(Packet.OuterPacketRpcIdLocation, sizeof(uint)), ref rpcId); +#endif + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private MemoryStreamBuffer Pack(ref uint rpcId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.UnPack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer().AsSpan(); +#if FANTASY_NET + MemoryMarshal.Write(buffer, in packetBodyCount); + MemoryMarshal.Write(buffer.Slice(Packet.PacketLength, sizeof(uint)), in opCode); + MemoryMarshal.Write(buffer.Slice(Packet.OuterPacketRpcIdLocation, sizeof(uint)), in rpcId); +#endif +#if FANTASY_UNITY + MemoryMarshal.Write(buffer, ref packetBodyCount); + MemoryMarshal.Write(buffer.Slice(Packet.PacketLength, sizeof(uint)), ref opCode); + MemoryMarshal.Write(buffer.Slice(Packet.OuterPacketRpcIdLocation, sizeof(uint)), ref rpcId); +#endif + return memoryStream; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta new file mode 100644 index 00000000..32698e58 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/BufferPacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0967856d30d1f464b82d88330920914a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs new file mode 100644 index 00000000..24c368b8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs @@ -0,0 +1,170 @@ +// using System.Runtime.CompilerServices; +// // ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// +// namespace Fantasy +// { +// // 这个对处理分包和粘包逻辑不完整、考虑现在没有任何地方使用了、就先不修改了。 +// // 后面用到了再修改、现在这个只是留做备份、万一以后用到了呢。 +// public abstract class CircularBufferPacketParser : APacketParser +// { +// protected uint RpcId; +// protected long RouteId; +// protected uint ProtocolCode; +// protected int MessagePacketLength; +// protected bool IsUnPackHead = true; +// protected readonly byte[] MessageHead = new byte[Packet.InnerPacketHeadLength]; +// public abstract bool UnPack(CircularBuffer buffer, out APackInfo packInfo); +// } +// +// #if FANTASY_NET +// public sealed class InnerCircularBufferPacketParser : CircularBufferPacketParser, IInnerPacketParser +// { +// public override bool UnPack(CircularBuffer buffer, out APackInfo packInfo) +// { +// packInfo = null; +// +// // 在对象没有被释放的情况下循环解析数据 +// while (!IsDisposed) +// { +// if (IsUnPackHead) +// { +// // 如果缓冲区中的数据长度小于内部消息头的长度,无法解析 +// if (buffer.Length < Packet.InnerPacketHeadLength) +// { +// return false; +// } +// +// // 从缓冲区中读取内部消息头的数据 +// _ = buffer.Read(MessageHead, 0, Packet.InnerPacketHeadLength); +// MessagePacketLength = BitConverter.ToInt32(MessageHead, 0); +// +// // 检查消息体长度是否超出限制 +// if (MessagePacketLength > Packet.PacketBodyMaxLength) +// { +// throw new ScanException( +// $"The received information exceeds the maximum limit = {MessagePacketLength}"); +// } +// +// // 解析协议编号、RPC ID 和 Route ID +// ProtocolCode = BitConverter.ToUInt32(MessageHead, Packet.PacketLength); +// RpcId = BitConverter.ToUInt32(MessageHead, Packet.InnerPacketRpcIdLocation); +// RouteId = BitConverter.ToInt64(MessageHead, Packet.InnerPacketRouteRouteIdLocation); +// IsUnPackHead = false; +// } +// +// try +// { +// // 如果缓冲区中的数据长度小于消息体的长度,无法解析 +// if (MessagePacketLength < 0 || buffer.Length < MessagePacketLength) +// { +// return false; +// } +// +// IsUnPackHead = true; +// packInfo = InnerPackInfo.Create(Network); +// var memoryStream = packInfo.RentMemoryStream(MessagePacketLength); +// memoryStream.SetLength(MessagePacketLength); +// buffer.Read(memoryStream, MessagePacketLength); +// packInfo.RpcId = RpcId; +// packInfo.RouteId = RouteId; +// packInfo.ProtocolCode = ProtocolCode; +// packInfo.MessagePacketLength = MessagePacketLength; +// return true; +// } +// catch (Exception e) +// { +// // 在发生异常时,释放 packInfo 并记录日志 +// packInfo?.Dispose(); +// Log.Error(e); +// return false; +// } +// } +// +// return false; +// } +// +// public override MemoryStream Pack(ref uint rpcId, ref long routeTypeOpCode, ref long routeId, +// MemoryStream memoryStream, object message) +// { +// return memoryStream == null +// ? Pack(ref rpcId, ref routeId, message) +// : Pack(ref rpcId, ref routeId, memoryStream); +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private unsafe MemoryStream Pack(ref uint rpcId, ref long routeId, MemoryStream memoryStream) +// { +// var buffer = memoryStream.GetBuffer(); +// +// fixed (byte* bufferPtr = buffer) +// { +// var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; +// var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; +// *(uint*)rpcIdPtr = rpcId; +// *(long*)routeIdPtr = routeId; +// } +// +// memoryStream.Seek(0, SeekOrigin.Begin); +// return memoryStream; +// } +// +// [MethodImpl(MethodImplOptions.AggressiveInlining)] +// private unsafe MemoryStream Pack(ref uint rpcId, ref long routeId, object message) +// { +// var memoryStream = Network.RentMemoryStream(); +// memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); +// +// switch (message) +// { +// case IBsonMessage: +// { +// MongoHelper.SerializeTo(message, memoryStream); +// break; +// } +// default: +// { +// ProtoBuffHelper.ToStream(message, memoryStream); +// break; +// } +// } +// +// var opCode = Scene.MessageDispatcherComponent.GetOpCode(message.GetType()); +// var packetBodyCount = (int)(memoryStream.Position - Packet.InnerPacketHeadLength); +// +// if (packetBodyCount == 0) +// { +// // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 +// // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 +// packetBodyCount = -1; +// } +// +// // 检查消息体长度是否超出限制 +// if (packetBodyCount > Packet.PacketBodyMaxLength) +// { +// throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); +// } +// +// var buffer = memoryStream.GetBuffer(); +// +// fixed (byte* bufferPtr = buffer) +// { +// var opCodePtr = bufferPtr + Packet.PacketLength; +// var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; +// var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; +// *(int*)bufferPtr = packetBodyCount; +// *(uint*)opCodePtr = opCode; +// *(uint*)rpcIdPtr = rpcId; +// *(long*)routeIdPtr = routeId; +// } +// +// memoryStream.Seek(0, SeekOrigin.Begin); +// return memoryStream; +// } +// } +// #endif +// } +// +// +// +// diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta new file mode 100644 index 00000000..375b2d6c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/CircularBufferPacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be4359634faca4ed99469ac0078203f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs new file mode 100644 index 00000000..a6e66ca3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs @@ -0,0 +1,72 @@ +#if FANTASY_NET +using System.Runtime.CompilerServices; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Serialize; + +namespace Fantasy.PacketParser +{ + /// + /// 打包Outer消息的帮助类 + /// + public static class OuterBufferPacketParserHelper + { + /// + /// 打包一个网络消息 + /// + /// scene + /// 如果是RPC消息需要传递一个rpcId + /// 打包的网络消息 + /// 序列化后流的长度 + /// 打包完成会返回一个MemoryStreamBuffer + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe MemoryStreamBuffer Pack(Scene scene, uint rpcId, IMessage message, out int memoryStreamLength) + { + memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = new MemoryStreamBuffer(); + memoryStream.MemoryStreamBufferSource = MemoryStreamBufferSource.Pack; + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(int*)bufferPtr = packetBodyCount; + *(uint*)(bufferPtr + Packet.PacketLength) = opCode; + *(uint*)(bufferPtr + Packet.OuterPacketRpcIdLocation) = rpcId; + } + + return memoryStream; + } + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta new file mode 100644 index 00000000..0a0785ee --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/OuterBufferPacketParserHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0d3a0cf7619f4a1db394e6dc0d8a089 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs new file mode 100644 index 00000000..758ec17c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs @@ -0,0 +1,357 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +namespace Fantasy.PacketParser +{ + internal abstract class ReadOnlyMemoryPacketParser : APacketParser + { + /// + /// 一个网络消息包 + /// + protected APackInfo PackInfo; + + protected int Offset; + protected int MessageHeadOffset; + protected int MessageBodyOffset; + protected int MessagePacketLength; + protected bool IsUnPackHead = true; + protected readonly byte[] MessageHead = new byte[20]; + public ReadOnlyMemoryPacketParser() { } + + public abstract bool UnPack(ref ReadOnlyMemory buffer, out APackInfo packInfo); + + public override void Dispose() + { + Offset = 0; + MessageHeadOffset = 0; + MessageBodyOffset = 0; + MessagePacketLength = 0; + IsUnPackHead = true; + PackInfo = null; + Array.Clear(MessageHead, 0, 20); + base.Dispose(); + } + } + +#if FANTASY_NET + internal sealed class InnerReadOnlyMemoryPacketParser : ReadOnlyMemoryPacketParser + { + public override unsafe bool UnPack(ref ReadOnlyMemory buffer, out APackInfo packInfo) + { + packInfo = null; + var readOnlySpan = buffer.Span; + var bufferLength = buffer.Length - Offset; + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + + if (IsUnPackHead) + { + fixed (byte* bufferPtr = readOnlySpan) + fixed (byte* messagePtr = MessageHead) + { + // 在当前buffer中拿到包头的数据 + var innerPacketHeadLength = Packet.InnerPacketHeadLength - MessageHeadOffset; + var copyLength = Math.Min(bufferLength, innerPacketHeadLength); + Buffer.MemoryCopy(bufferPtr + Offset, messagePtr + MessageHeadOffset, innerPacketHeadLength, copyLength); + Offset += copyLength; + MessageHeadOffset += copyLength; + // 检查是否有完整包头 + if (MessageHeadOffset == Packet.InnerPacketHeadLength) + { + // 通过指针直接读取协议编号、messagePacketLength protocolCode rpcId routeId + MessagePacketLength = *(int*)messagePtr; + // 检查消息体长度是否超出限制 + if (MessagePacketLength > Packet.PacketBodyMaxLength) + { + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + PackInfo = InnerPackInfo.Create(Network); + var memoryStream = PackInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, Packet.InnerPacketHeadLength + MessagePacketLength); + PackInfo.RpcId = *(uint*)(messagePtr + Packet.InnerPacketRpcIdLocation); + PackInfo.ProtocolCode = *(uint*)(messagePtr + Packet.PacketLength); + PackInfo.RouteId = *(long*)(messagePtr + Packet.InnerPacketRouteRouteIdLocation); + memoryStream.Write(MessageHead); + IsUnPackHead = false; + bufferLength -= copyLength; + MessageHeadOffset = 0; + } + else + { + Offset = 0; + return false; + } + } + } + + if (MessagePacketLength == -1) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + return true; + } + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + + // 处理包消息体 + var innerPacketBodyLength = MessagePacketLength - MessageBodyOffset; + var copyBodyLength = Math.Min(bufferLength, innerPacketBodyLength); + // 写入数据到消息体中 + PackInfo.MemoryStream.Write(readOnlySpan.Slice(Offset, copyBodyLength)); + Offset += copyBodyLength; + MessageBodyOffset += copyBodyLength; + // 检查是否是完整的消息体 + if (MessageBodyOffset == MessagePacketLength) + { + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + MessageBodyOffset = 0; + return true; + } + Offset = 0; + return false; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, ref routeId, message) : Pack(ref rpcId, ref routeId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream) + { + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(uint*)(bufferPtr + Packet.InnerPacketRpcIdLocation) = rpcId; + *(long*)(bufferPtr + Packet.InnerPacketRouteRouteIdLocation) = routeId; + } + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.InnerPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + // 其实可以不用设置-1、解包的时候判断如果是0也可以、但我仔细想了下,还是用-1代表更加清晰。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(int*)bufferPtr = packetBodyCount; + *(uint*)(bufferPtr + Packet.PacketLength) = opCode; + *(uint*)(bufferPtr + Packet.InnerPacketRpcIdLocation) = rpcId; + *(long*)(bufferPtr + Packet.InnerPacketRouteRouteIdLocation) = routeId; + } + + return memoryStream; + } + } +#endif + internal sealed class OuterReadOnlyMemoryPacketParser : ReadOnlyMemoryPacketParser + { + public override unsafe bool UnPack(ref ReadOnlyMemory buffer, out APackInfo packInfo) + { + packInfo = null; + var readOnlySpan = buffer.Span; + var bufferLength = buffer.Length - Offset; + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + + if (IsUnPackHead) + { + fixed (byte* bufferPtr = readOnlySpan) + fixed (byte* messagePtr = MessageHead) + { + // 在当前buffer中拿到包头的数据 + var outerPacketHeadLength = Packet.OuterPacketHeadLength - MessageHeadOffset; + var copyLength = Math.Min(bufferLength, outerPacketHeadLength); + Buffer.MemoryCopy(bufferPtr + Offset, messagePtr + MessageHeadOffset, outerPacketHeadLength, copyLength); + Offset += copyLength; + MessageHeadOffset += copyLength; + // 检查是否有完整包头 + if (MessageHeadOffset == Packet.OuterPacketHeadLength) + { + // 通过指针直接读取协议编号、messagePacketLength protocolCode rpcId routeId + MessagePacketLength = *(int*)messagePtr; + // 检查消息体长度是否超出限制 + if (MessagePacketLength > Packet.PacketBodyMaxLength) + { + throw new ScanException($"The received information exceeds the maximum limit = {MessagePacketLength}"); + } + + PackInfo = OuterPackInfo.Create(Network); + PackInfo.ProtocolCode = *(uint*)(messagePtr + Packet.PacketLength); + PackInfo.RpcId = *(uint*)(messagePtr + Packet.OuterPacketRpcIdLocation); + var memoryStream = PackInfo.RentMemoryStream(MemoryStreamBufferSource.UnPack, Packet.OuterPacketHeadLength + MessagePacketLength); + memoryStream.Write(MessageHead); + IsUnPackHead = false; + bufferLength -= copyLength; + MessageHeadOffset = 0; + } + else + { + Offset = 0; + return false; + } + } + } + + if (MessagePacketLength == -1) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + return true; + } + + if (bufferLength == 0) + { + // 没有剩余的数据需要处理、等待下一个包再处理。 + Offset = 0; + return false; + } + // 处理包消息体 + var outerPacketBodyLength = MessagePacketLength - MessageBodyOffset; + var copyBodyLength = Math.Min(bufferLength, outerPacketBodyLength); + // 写入数据到消息体中 + PackInfo.MemoryStream.Write(readOnlySpan.Slice(Offset, copyBodyLength)); + Offset += copyBodyLength; + MessageBodyOffset += copyBodyLength; + // 检查是否是完整的消息体 + if (MessageBodyOffset == MessagePacketLength) + { + packInfo = PackInfo; + PackInfo = null; + IsUnPackHead = true; + MessageBodyOffset = 0; + return true; + } + + Offset = 0; + return false; + } + + public override MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + return memoryStream == null ? Pack(ref rpcId, message) : Pack(ref rpcId, memoryStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, MemoryStreamBuffer memoryStream) + { + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(uint*)(bufferPtr + Packet.OuterPacketRpcIdLocation) = rpcId; + } + + return memoryStream; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private unsafe MemoryStreamBuffer Pack(ref uint rpcId, IMessage message) + { + var memoryStreamLength = 0; + var messageType = message.GetType(); + var memoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.Pack); + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{messageType} Does not support processing protocol"); + } + + var opCode = Scene.MessageDispatcherComponent.GetOpCode(messageType); + var packetBodyCount = memoryStreamLength - Packet.OuterPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + fixed (byte* bufferPtr = memoryStream.GetBuffer()) + { + *(int*)bufferPtr = packetBodyCount; + *(uint*)(bufferPtr + Packet.PacketLength) = opCode; + *(uint*)(bufferPtr + Packet.OuterPacketRpcIdLocation) = rpcId; + } + + return memoryStream; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta new file mode 100644 index 00000000..cfa37d96 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Handler/ReadOnlyMemoryPacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba02e3545888e431f896b40c391db7a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface.meta new file mode 100644 index 00000000..815a8cfa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c6a95f4bea72e435fba91ccf6f77883f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APackInfo.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APackInfo.cs new file mode 100644 index 00000000..1ea6d6b5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APackInfo.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.PacketParser.Interface +{ + public abstract class APackInfo : IDisposable + { + internal ANetwork Network; + + public uint RpcId; + public long RouteId; + public long PackInfoId; + public bool IsDisposed; + private uint _protocolCode; + + public uint ProtocolCode + { + get => _protocolCode; + set + { + _protocolCode = value; + OpCodeIdStruct = value; + } + } + public OpCodeIdStruct OpCodeIdStruct { get; private set; } + public MemoryStreamBuffer MemoryStream { get; protected set; } + public abstract object Deserialize(Type messageType); + public abstract MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0); + public virtual void Dispose() + { + if (IsDisposed) + { + return; + } + + RpcId = 0; + RouteId = 0; + PackInfoId = 0; + ProtocolCode = 0; + _protocolCode = 0; + OpCodeIdStruct = default; + + if (MemoryStream != null) + { + Network.MemoryStreamBufferPool.ReturnMemoryStream(MemoryStream); + MemoryStream = null; + } + + IsDisposed = true; + Network = null; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta new file mode 100644 index 00000000..41d09273 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0cb78fb80aac6490cb0fde6f38195b3b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APacketParser.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APacketParser.cs new file mode 100644 index 00000000..579cf6ff --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APacketParser.cs @@ -0,0 +1,30 @@ +using System; +using System.Buffers; +using System.IO; +using Fantasy.Network.Interface; +using Fantasy.Serialize; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.PacketParser.Interface +{ + /// + /// 抽象的包解析器基类,用于解析网络通信数据包。 + /// + public abstract class APacketParser : IDisposable + { + internal Scene Scene; + internal ANetwork Network; + internal MessageDispatcherComponent MessageDispatcherComponent; + protected bool IsDisposed { get; private set; } + public abstract MemoryStreamBuffer Pack(ref uint rpcId, ref long routeId, MemoryStreamBuffer memoryStream, IMessage message); + public virtual void Dispose() + { + IsDisposed = true; + Scene = null; + MessageDispatcherComponent = null; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta new file mode 100644 index 00000000..e1bbd00d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Interface/APacketParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b61358c7f6d9f4b58a26d9a57b79ba45 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/OpCode.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/OpCode.cs new file mode 100644 index 00000000..d02105d9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/OpCode.cs @@ -0,0 +1,106 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network +{ + public struct OpCodeIdStruct + { + // OpCodeIdStruct:5 + 4 + 23 = 32 + // +---------------------------+---------------------------------+-----------------------------+ + // | OpCodeType(5) 最多31种类型 | Protocol(4) 最多15种不同的网络协议 | Index(23) 最多8388607个协议 | + // +---------------------------+---------------------------------+-----------------------------+ + public uint OpCodeProtocolType { get; private set; } + public uint Protocol { get; private set; } + public uint Index { get; private set; } + + public OpCodeIdStruct(uint opCodeProtocolType, uint protocol, uint index) + { + OpCodeProtocolType = opCodeProtocolType; + Protocol = protocol; + Index = index; + } + + public static implicit operator uint(OpCodeIdStruct opCodeIdStruct) + { + var result = opCodeIdStruct.Index; + result |= opCodeIdStruct.OpCodeProtocolType << 23; + result |= opCodeIdStruct.Protocol << 27; + return result; + } + + public static implicit operator OpCodeIdStruct(uint opCodeId) + { + var opCodeIdStruct = new OpCodeIdStruct() + { + Index = opCodeId & 0x7FFFFF + }; + opCodeId >>= 23; + opCodeIdStruct.OpCodeProtocolType = opCodeId & 0xF; + opCodeId >>= 4; + opCodeIdStruct.Protocol = opCodeId & 0x1F; + return opCodeIdStruct; + } + } + + public static class OpCodeProtocolType + { + public const uint Bson = 1; + public const uint ProtoBuf = 0; + } + + public static class OpCodeType + { + public const uint OuterMessage = 1; + public const uint OuterRequest = 2; + public const uint OuterResponse = 3; + + public const uint InnerMessage = 4; + public const uint InnerRequest = 5; + public const uint InnerResponse = 6; + + public const uint InnerRouteMessage = 7; + public const uint InnerRouteRequest = 8; + public const uint InnerRouteResponse = 9; + + public const uint OuterAddressableMessage = 10; + public const uint OuterAddressableRequest = 11; + public const uint OuterAddressableResponse = 12; + + public const uint InnerAddressableMessage = 13; + public const uint InnerAddressableRequest = 14; + public const uint InnerAddressableResponse = 15; + + public const uint OuterCustomRouteMessage = 16; + public const uint OuterCustomRouteRequest = 17; + public const uint OuterCustomRouteResponse = 18; + + public const uint OuterPingRequest = 19; + public const uint OuterPingResponse = 20; + } + + public static class OpCode + { + public static readonly uint BenchmarkMessage = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterMessage, 8388607); + public static readonly uint BenchmarkRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterRequest, 8388607); + public static readonly uint BenchmarkResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterResponse, 8388607); + public static readonly uint PingRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterPingRequest, 1); + public static readonly uint PingResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.OuterPingResponse, 1); + public static readonly uint DefaultResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerResponse, 1); + public static readonly uint DefaultRouteResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 7); + public static readonly uint AddressableAddRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 1); + public static readonly uint AddressableAddResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 1); + public static readonly uint AddressableGetRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 2); + public static readonly uint AddressableGetResponse = Create(OpCodeProtocolType.ProtoBuf,OpCodeType.InnerRouteResponse,2); + public static readonly uint AddressableRemoveRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 3); + public static readonly uint AddressableRemoveResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 3); + public static readonly uint AddressableLockRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 4); + public static readonly uint AddressableLockResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 4); + public static readonly uint AddressableUnLockRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 5); + public static readonly uint AddressableUnLockResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 5); + public static readonly uint LinkEntityRequest = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteRequest, 6); + public static readonly uint LinkEntityResponse = Create(OpCodeProtocolType.ProtoBuf, OpCodeType.InnerRouteResponse, 6); + + public static uint Create(uint opCodeProtocolType, uint protocol, uint index) + { + return new OpCodeIdStruct(opCodeProtocolType, protocol, index); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/OpCode.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/OpCode.cs.meta new file mode 100644 index 00000000..ce6d4982 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/OpCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d44622c27a8c41048e995d634974dba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack.meta new file mode 100644 index 00000000..9e6ad48f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 43e4eed87e2c24c12b3d7f1be3382c25 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs new file mode 100644 index 00000000..e9870e72 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs @@ -0,0 +1,79 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Pool; +using Fantasy.Serialize; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. +#if FANTASY_NET +namespace Fantasy.PacketParser +{ + public sealed class InnerPackInfo : APackInfo + { + private readonly Dictionary> _createInstances = new Dictionary>(); + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + var network = Network; + base.Dispose(); + network.ReturnInnerPackInfo(this); + } + + public static InnerPackInfo Create(ANetwork network) + { + var innerPackInfo = network.RentInnerPackInfo(); + innerPackInfo.Network = network; + innerPackInfo.IsDisposed = false; + return innerPackInfo; + } + + public override MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + return MemoryStream ??= Network.MemoryStreamBufferPool.RentMemoryStream(memoryStreamBufferSource, size); + } + + public override object Deserialize(Type messageType) + { + if (MemoryStream == null) + { + Log.Debug("Deserialize MemoryStream is null"); + return null; + } + + MemoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (MemoryStream.Length == 0) + { + if (_createInstances.TryGetValue(messageType, out var createInstance)) + { + return createInstance(); + } + + createInstance = CreateInstance.CreateObject(messageType); + _createInstances.Add(messageType, createInstance); + return createInstance(); + } + + if (SerializerManager.TryGetSerializer(OpCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + var obj = serializer.Deserialize(messageType, MemoryStream); + MemoryStream.Seek(0, SeekOrigin.Begin); + return obj; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + Log.Error($"protocolCode:{ProtocolCode} Does not support processing protocol"); + return null; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta new file mode 100644 index 00000000..b5e37e11 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/InnerPackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7324100bcab9421b9534820f3274b7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs new file mode 100644 index 00000000..8ce08b7c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs @@ -0,0 +1,73 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System; +using System.IO; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Serialize; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +namespace Fantasy.PacketParser +{ + public sealed class OuterPackInfo : APackInfo + { + public override void Dispose() + { + if (IsDisposed) + { + return; + } + var network = Network; + base.Dispose(); + network.ReturnOuterPackInfo(this); + } + + public static OuterPackInfo Create(ANetwork network) + { + var outerPackInfo = network.RentOuterPackInfo(); + outerPackInfo.Network = network; + outerPackInfo.IsDisposed = false; + return outerPackInfo; + } + + public override MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + if (MemoryStream == null) + { + MemoryStream = Network.MemoryStreamBufferPool.RentMemoryStream(memoryStreamBufferSource, size); + } + + return MemoryStream; + } + + /// + /// 将消息数据从内存反序列化为指定的消息类型实例。 + /// + /// 目标消息类型。 + /// 反序列化后的消息类型实例。 + public override object Deserialize(Type messageType) + { + if (MemoryStream == null) + { + Log.Debug("Deserialize MemoryStream is null"); + return null; + } + + MemoryStream.Seek(Packet.OuterPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(OpCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + var obj = serializer.Deserialize(messageType, MemoryStream); + MemoryStream.Seek(0, SeekOrigin.Begin); + return obj; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + Log.Error($"protocolCode:{ProtocolCode} Does not support processing protocol"); + return null; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta new file mode 100644 index 00000000..66f848f7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/OuterPackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 089b5fa434fce46a3898f46df31c53d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs new file mode 100644 index 00000000..f0108585 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs @@ -0,0 +1,160 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +using Fantasy.Pool; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.PacketParser +{ + public sealed class ProcessPackInfo : APackInfo + { + private int _disposeCount; + public Type MessageType { get; private set; } + private static readonly ConcurrentQueue Caches = new ConcurrentQueue(); + private readonly ConcurrentDictionary> _createInstances = new ConcurrentDictionary>(); + + public override void Dispose() + { + if (--_disposeCount > 0 || IsDisposed) + { + return; + } + + _disposeCount = 0; + MessageType = null; + base.Dispose(); + + if (Caches.Count > 2000) + { + return; + } + + Caches.Enqueue(this); + } + + public static unsafe ProcessPackInfo Create(Scene scene, T message, int disposeCount, uint rpcId = 0, long routeId = 0) where T : IRouteMessage + { + if (!Caches.TryDequeue(out var packInfo)) + { + packInfo = new ProcessPackInfo(); + } + + var type = typeof(T); + var memoryStreamLength = 0; + packInfo._disposeCount = disposeCount; + packInfo.MessageType = type; + packInfo.IsDisposed = false; + var memoryStream = new MemoryStreamBuffer(); + memoryStream.MemoryStreamBufferSource = MemoryStreamBufferSource.Pack; + OpCodeIdStruct opCodeIdStruct = message.OpCode(); + memoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(type, message, memoryStream); + memoryStreamLength = (int)memoryStream.Position; + } + else + { + Log.Error($"type:{type} Does not support processing protocol"); + } + + var opCode = scene.MessageDispatcherComponent.GetOpCode(packInfo.MessageType); + var packetBodyCount = memoryStreamLength - Packet.InnerPacketHeadLength; + + if (packetBodyCount == 0) + { + // protoBuf做了一个优化、就是当序列化的对象里的属性和字段都为默认值的时候就不会序列化任何东西。 + // 为了TCP的分包和粘包、需要判定下是当前包数据不完整还是本应该如此、所以用-1代表。 + packetBodyCount = -1; + } + + if (packetBodyCount > Packet.PacketBodyMaxLength) + { + // 检查消息体长度是否超出限制 + throw new Exception($"Message content exceeds {Packet.PacketBodyMaxLength} bytes"); + } + + var buffer = memoryStream.GetBuffer(); + + fixed (byte* bufferPtr = buffer) + { + var opCodePtr = bufferPtr + Packet.PacketLength; + var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; + var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; + *(int*)bufferPtr = packetBodyCount; + *(uint*)opCodePtr = opCode; + *(uint*)rpcIdPtr = rpcId; + *(long*)routeIdPtr = routeId; + } + + memoryStream.Seek(0, SeekOrigin.Begin); + packInfo.MemoryStream = memoryStream; + return packInfo; + } + + public unsafe void Set(uint rpcId, long routeId) + { + var buffer = MemoryStream.GetBuffer(); + + fixed (byte* bufferPtr = buffer) + { + var rpcIdPtr = bufferPtr + Packet.InnerPacketRpcIdLocation; + var routeIdPtr = bufferPtr + Packet.InnerPacketRouteRouteIdLocation; + *(uint*)rpcIdPtr = rpcId; + *(long*)routeIdPtr = routeId; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + } + + public override MemoryStreamBuffer RentMemoryStream(MemoryStreamBufferSource memoryStreamBufferSource, int size = 0) + { + throw new NotImplementedException(); + } + + public override object Deserialize(Type messageType) + { + if (MemoryStream == null) + { + Log.Debug("Deserialize MemoryStream is null"); + return null; + } + + object obj = null; + MemoryStream.Seek(Packet.InnerPacketHeadLength, SeekOrigin.Begin); + + if (MemoryStream.Length == 0) + { + if (_createInstances.TryGetValue(messageType, out var createInstance)) + { + return createInstance(); + } + + createInstance = CreateInstance.CreateObject(messageType); + _createInstances.TryAdd(messageType, createInstance); + return createInstance(); + } + + if (SerializerManager.TryGetSerializer(OpCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + obj = serializer.Deserialize(messageType, MemoryStream); + MemoryStream.Seek(0, SeekOrigin.Begin); + return obj; + } + + MemoryStream.Seek(0, SeekOrigin.Begin); + Log.Error($"protocolCode:{ProtocolCode} Does not support processing protocol"); + return null; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta new file mode 100644 index 00000000..dc55c46f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Pack/ProcessPackInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 703b20fc55fb240df9156adfa9919907 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Packet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Packet.cs new file mode 100644 index 00000000..7198af74 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Packet.cs @@ -0,0 +1,49 @@ +namespace Fantasy.PacketParser +{ + /// + /// 提供关于消息包的常量定义。 + /// + public struct Packet + { + /// + /// 消息体最大长度 + /// + public const int PacketBodyMaxLength = ushort.MaxValue * 16; + /// + /// 消息体长度在消息头占用的长度 + /// + public const int PacketLength = sizeof(int); + /// + /// 协议编号在消息头占用的长度 + /// + public const int ProtocolCodeLength = sizeof(uint); + /// + /// RouteId长度 + /// + public const int PacketRouteIdLength = sizeof(long); + /// + /// RpcId在消息头占用的长度 + /// + public const int RpcIdLength = sizeof(uint); + /// + /// OuterRPCId所在的位置 + /// + public const int OuterPacketRpcIdLocation = PacketLength + ProtocolCodeLength; + /// + /// InnerRPCId所在的位置 + /// + public const int InnerPacketRpcIdLocation = PacketLength + ProtocolCodeLength; + /// + /// RouteId所在的位置 + /// + public const int InnerPacketRouteRouteIdLocation = PacketLength + ProtocolCodeLength + RpcIdLength; + /// + /// 外网消息头长度(消息体长度在消息头占用的长度 + 协议编号在消息头占用的长度 + RPCId长度 + RouteId长度) + /// + public const int OuterPacketHeadLength = PacketLength + ProtocolCodeLength + RpcIdLength + PacketRouteIdLength; + /// + /// 内网消息头长度(消息体长度在消息头占用的长度 + 协议编号在消息头占用的长度 + RPCId长度 + RouteId长度) + /// + public const int InnerPacketHeadLength = PacketLength + ProtocolCodeLength + RpcIdLength + PacketRouteIdLength; + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Packet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Packet.cs.meta new file mode 100644 index 00000000..146d1f06 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/Packet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b788ac48105e5489b97079cb9f94991e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/PacketParserFactory.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/PacketParserFactory.cs new file mode 100644 index 00000000..679f95dc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/PacketParserFactory.cs @@ -0,0 +1,173 @@ +using System; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; + +// ReSharper disable PossibleNullReferenceException +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. +namespace Fantasy.PacketParser +{ + internal static class PacketParserFactory + { +#if FANTASY_NET + internal static ReadOnlyMemoryPacketParser CreateServerReadOnlyMemoryPacket(ANetwork network) + { + ReadOnlyMemoryPacketParser readOnlyMemoryPacketParser = null; + + switch (network.NetworkTarget) + { + case NetworkTarget.Inner: + { + readOnlyMemoryPacketParser = new InnerReadOnlyMemoryPacketParser(); + break; + } + case NetworkTarget.Outer: + { + readOnlyMemoryPacketParser = new OuterReadOnlyMemoryPacketParser(); + break; + } + } + + readOnlyMemoryPacketParser.Scene = network.Scene; + readOnlyMemoryPacketParser.Network = network; + readOnlyMemoryPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return readOnlyMemoryPacketParser; + } + + public static BufferPacketParser CreateServerBufferPacket(ANetwork network) + { + BufferPacketParser bufferPacketParser = null; + + switch (network.NetworkTarget) + { + case NetworkTarget.Inner: + { + bufferPacketParser = new InnerBufferPacketParser(); + break; + } + case NetworkTarget.Outer: + { + bufferPacketParser = new OuterBufferPacketParser(); + break; + } + } + + bufferPacketParser.Scene = network.Scene; + bufferPacketParser.Network = network; + bufferPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return bufferPacketParser; + } +#endif + internal static ReadOnlyMemoryPacketParser CreateClientReadOnlyMemoryPacket(ANetwork network) + { + ReadOnlyMemoryPacketParser readOnlyMemoryPacketParser = null; + + switch (network.NetworkTarget) + { +#if FANTASY_NET + case NetworkTarget.Inner: + { + readOnlyMemoryPacketParser = new InnerReadOnlyMemoryPacketParser(); + break; + } +#endif + case NetworkTarget.Outer: + { + readOnlyMemoryPacketParser = new OuterReadOnlyMemoryPacketParser(); + break; + } + } + + readOnlyMemoryPacketParser.Scene = network.Scene; + readOnlyMemoryPacketParser.Network = network; + readOnlyMemoryPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return readOnlyMemoryPacketParser; + } + +#if !FANTASY_WEBGL + public static BufferPacketParser CreateClientBufferPacket(ANetwork network) + { + BufferPacketParser bufferPacketParser = null; + + switch (network.NetworkTarget) + { +#if FANTASY_NET + case NetworkTarget.Inner: + { + bufferPacketParser = new InnerBufferPacketParser(); + break; + } +#endif + case NetworkTarget.Outer: + { + bufferPacketParser = new OuterBufferPacketParser(); + break; + } + } + + bufferPacketParser.Scene = network.Scene; + bufferPacketParser.Network = network; + bufferPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return bufferPacketParser; + } +#endif + public static T CreateClient(ANetwork network) where T : APacketParser + { + var packetParserType = typeof(T); + + switch (network.NetworkTarget) + { +#if FANTASY_NET + case NetworkTarget.Inner: + { + APacketParser innerPacketParser = null; + + if (packetParserType == typeof(ReadOnlyMemoryPacketParser)) + { + innerPacketParser = new InnerReadOnlyMemoryPacketParser(); + } + else if (packetParserType == typeof(BufferPacketParser)) + { + innerPacketParser = new InnerBufferPacketParser(); + } + // else if(packetParserType == typeof(CircularBufferPacketParser)) + // { + // innerPacketParser = new InnerCircularBufferPacketParser(); + // } + + innerPacketParser.Scene = network.Scene; + innerPacketParser.Network = network; + innerPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return (T)innerPacketParser; + } +#endif + case NetworkTarget.Outer: + { + APacketParser outerPacketParser = null; + + if (packetParserType == typeof(ReadOnlyMemoryPacketParser)) + { + outerPacketParser = new OuterReadOnlyMemoryPacketParser(); + } + else if (packetParserType == typeof(BufferPacketParser)) + { +#if FANTASY_WEBGL + outerPacketParser = new OuterWebglBufferPacketParser(); +#else + outerPacketParser = new OuterBufferPacketParser(); +#endif + } + outerPacketParser.Scene = network.Scene; + outerPacketParser.Network = network; + outerPacketParser.MessageDispatcherComponent = network.Scene.MessageDispatcherComponent; + return (T)outerPacketParser; + } + default: + throw new ArgumentOutOfRangeException(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta new file mode 100644 index 00000000..f7b450d0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/PacketParser/PacketParserFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 555f2f9f48ed7406aaf831443714053c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler.meta new file mode 100644 index 00000000..0a84f660 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6bc659d65dda643d0bb0134c9c222523 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs new file mode 100644 index 00000000..30f8d125 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs @@ -0,0 +1,91 @@ +using System; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Scheduler +{ +#if FANTASY_UNITY || FANTASY_CONSOLE + /// + /// 提供了一个用于客户端网络消息调度和处理的抽象基类。 + /// + public sealed class ClientMessageScheduler : ANetworkMessageScheduler + { + public ClientMessageScheduler(Scene scene) : base(scene) { } + + public override void Scheduler(Session session, APackInfo packInfo) + { + switch (packInfo.OpCodeIdStruct.Protocol) + { + case OpCodeType.OuterMessage: + case OpCodeType.OuterRequest: + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterCustomRouteMessage: + case OpCodeType.OuterCustomRouteRequest: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var message = packInfo.Deserialize(messageType); + MessageDispatcherComponent.MessageHandler(session, messageType, message, packInfo.RpcId, packInfo.ProtocolCode); + } + + return; + } + case OpCodeType.OuterResponse: + case OpCodeType.OuterPingResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + // 这个一般是客户端Session.Call发送时使用的、目前这个逻辑只有Unity客户端时使用 + + var aResponse = (IResponse)packInfo.Deserialize(messageType); + + if (!session.RequestCallback.Remove(packInfo.RpcId, out var action)) + { + Log.Error($"not found rpc {packInfo.RpcId}, response message: {aResponse.GetType().Name}"); + return; + } + + action.TrySetResult(aResponse); + } + + return; + } + default: + { + packInfo.Dispose(); + throw new NotSupportedException($"Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } + } + } +#endif +#if FANTASY_NET + internal sealed class ClientMessageScheduler(Scene scene) : ANetworkMessageScheduler(scene) + { + public override void Scheduler(Session session, APackInfo packInfo) + { + throw new NotSupportedException($"ClientMessageScheduler Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } +#endif +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta new file mode 100644 index 00000000..45ad9be7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/ClientMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 98e138214f0e74a7687aa06ffdce555e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs new file mode 100644 index 00000000..6486bcc6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs @@ -0,0 +1,201 @@ +#if FANTASY_NET +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System.Runtime.CompilerServices; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Scheduler +{ + /// + /// 提供了一个机制来调度和处理内部网络消息。 + /// + internal sealed class InnerMessageScheduler(Scene scene) : ANetworkMessageScheduler(scene) + { + public override void Scheduler(Session session, APackInfo packInfo) + { + var protocol = packInfo.OpCodeIdStruct.Protocol; + + switch (protocol) + { + case OpCodeType.InnerMessage: + case OpCodeType.InnerRequest: + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + try + { + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var message = packInfo.Deserialize(messageType); + MessageDispatcherComponent.MessageHandler(session, messageType, message, packInfo.RpcId, packInfo.ProtocolCode); + } + catch (Exception e) + { + Log.Error($"ANetworkMessageScheduler OuterResponse error messageProtocolCode:{packInfo.ProtocolCode} messageType:{messageType} SessionId {session.Id} IsDispose {session.IsDisposed} {e}"); + } + finally + { + packInfo.Dispose(); + } + + return; + } + case OpCodeType.InnerResponse: + case OpCodeType.InnerRouteResponse: + case OpCodeType.InnerAddressableResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + NetworkMessagingComponent.ResponseHandler(packInfo.RpcId, (IResponse)packInfo.Deserialize(messageType)); + } + + return; + } + case OpCodeType.InnerRouteMessage: + case OpCodeType.InnerAddressableMessage: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"InnerMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + if (!Scene.TryGetEntity(packInfo.RouteId, out var entity)) + { + throw new Exception($"The Entity associated with RouteId = {packInfo.RouteId} was not found! messageType = {messageType.FullName}"); + } + + var obj = packInfo.Deserialize(messageType); + Scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, (IMessage)obj, packInfo.RpcId).Coroutine(); + } + + return; + } + case OpCodeType.InnerRouteRequest: + case OpCodeType.InnerAddressableRequest: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"InnerMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + if (!Scene.TryGetEntity(packInfo.RouteId, out var entity)) + { + Scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, packInfo.RpcId); + } + + var obj = packInfo.Deserialize(messageType); + Scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, (IMessage)obj, packInfo.RpcId).Coroutine(); + } + + return; + } + case OpCodeType.OuterCustomRouteRequest: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterCustomRouteMessage: + { + var entity = Scene.GetEntity(packInfo.RouteId); + + switch (entity) + { + case null: + { + // 执行到这里有两种情况: + using (packInfo) + { + switch (Scene.SceneConfig.SceneTypeString) + { + case "Gate": + { + // 1、当前是Gate进行,需要转发消息给客户端,但当前这个Session已经断开了。 + // 这种情况不需要做任何处理。 + return; + } + default: + { + // 2、当前是其他Scene、消息通过Gate发送到这个Scene上面,但这个Scene上面没有这个Entity。 + // 因为这个是Gate转发消息到这个Scene的,如果没有找到Entity要返回错误给Gate。 + // 出现这个情况一定要打印日志,因为出现这个问题肯定是上层逻辑导致的,不应该出现这样的问题。 + var packInfoRouteId = packInfo.RouteId; + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + switch (protocol) + { + case OpCodeType.OuterCustomRouteRequest: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterAddressableMessage: + { + Scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, packInfo.RpcId); + return; + } + } + + throw new Exception($"The Entity associated with RouteId = {packInfoRouteId} was not found! messageType = {messageType.FullName} protocol = {protocol}"); + } + } + } + } + case Session gateSession: + { + using (packInfo) + { + // 这里如果是Session只可能是Gate的Session、如果是的话、肯定是转发消息 + gateSession.Send(packInfo.MemoryStream, packInfo.RpcId); + } + + return; + } + default: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"InnerMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var obj = packInfo.Deserialize(messageType); + Scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, (IMessage)obj, packInfo.RpcId).Coroutine(); + } + + return; + } + } + } + default: + { + var infoProtocolCode = packInfo.ProtocolCode; + packInfo.Dispose(); + throw new NotSupportedException($"InnerMessageScheduler Received unsupported message protocolCode:{infoProtocolCode}"); + } + } + } + } +} +#endif + diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta new file mode 100644 index 00000000..7133aa9a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/InnerMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9e7e2db0df3c345ddab6ce79df0db347 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface.meta new file mode 100644 index 00000000..b4ea2d08 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a25819b011d8c49819efde1122c75a7d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs new file mode 100644 index 00000000..cff96b22 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs @@ -0,0 +1,26 @@ +using System; +using System.IO; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable UnassignedField.Global +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.Scheduler +{ + public abstract class ANetworkMessageScheduler + { + protected readonly Scene Scene; + protected readonly MessageDispatcherComponent MessageDispatcherComponent; + protected readonly NetworkMessagingComponent NetworkMessagingComponent; + protected ANetworkMessageScheduler(Scene scene) + { + Scene = scene; + MessageDispatcherComponent = scene.MessageDispatcherComponent; + NetworkMessagingComponent = scene.NetworkMessagingComponent; + } + public abstract void Scheduler(Session session, APackInfo packInfo); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta new file mode 100644 index 00000000..add81334 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/Interface/ANetworkMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b66f417f0af774145a9bd64c0ec933e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper.meta new file mode 100644 index 00000000..08f554b8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 17461e5c3d2cd41a1a11b4c92890b8ce +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs new file mode 100644 index 00000000..fbcd1ba5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs @@ -0,0 +1,108 @@ +using System; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network.Interface; + +#pragma warning disable CS8625 +#pragma warning disable CS8618 + +namespace Fantasy.Scheduler +{ + /// + /// 网络消息发送者的类。 + /// + public struct MessageSender : IDisposable + { + /// + /// 获取或设置 RPC ID。 + /// + public uint RpcId { get; private set; } + /// + /// 获取或设置路由 ID。 + /// + public long RouteId { get; private set; } + /// + /// 获取或设置创建时间。 + /// + public long CreateTime { get; private set; } + /// + /// 获取或设置消息类型。 + /// + public Type MessageType { get; private set; } + /// + /// 获取或设置请求消息。 + /// + public IMessage Request { get; private set; } + /// + /// 获取或设置任务。 + /// + public AutoResetUniTaskCompletionSourcePlus Tcs { get; private set; } + + /// + /// 释放资源。 + /// + public void Dispose() + { + RpcId = 0; + RouteId = 0; + CreateTime = 0; + Tcs = null; + Request = null; + MessageType = null; + } + + /// + /// 创建一个 实例。 + /// + /// RPC ID。 + /// 请求消息类型。 + /// 任务。 + /// 创建的 实例。 + public static MessageSender Create(uint rpcId, Type requestType, AutoResetUniTaskCompletionSourcePlus tcs) + { + var routeMessageSender = new MessageSender(); + routeMessageSender.Tcs = tcs; + routeMessageSender.RpcId = rpcId; + routeMessageSender.MessageType = requestType; + routeMessageSender.CreateTime = TimeHelper.Now; + return routeMessageSender; + } + + /// + /// 创建一个 实例。 + /// + /// RPC ID。 + /// 请求消息。 + /// 任务。 + /// 创建的 实例。 + public static MessageSender Create(uint rpcId, IRequest request, AutoResetUniTaskCompletionSourcePlus tcs) + { + var routeMessageSender = new MessageSender(); + routeMessageSender.Tcs = tcs; + routeMessageSender.RpcId = rpcId; + routeMessageSender.Request = request; + routeMessageSender.CreateTime = TimeHelper.Now; + return routeMessageSender; + } + + /// + /// 创建一个 实例。 + /// + /// RPC ID。 + /// 路由 ID。 + /// 路由消息请求。 + /// 任务。 + /// 创建的 实例。 + public static MessageSender Create(uint rpcId, long routeId, IRouteMessage request, AutoResetUniTaskCompletionSourcePlus tcs) + { + var routeMessageSender = new MessageSender(); + routeMessageSender.Tcs = tcs; + routeMessageSender.RpcId = rpcId; + routeMessageSender.RouteId = routeId; + routeMessageSender.Request = request; + routeMessageSender.CreateTime = TimeHelper.Now; + return routeMessageSender; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta new file mode 100644 index 00000000..0e7aab10 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/MessageSender.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57d40c852547547f0a8022bf3b4f6f91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs new file mode 100644 index 00000000..c498aa57 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs @@ -0,0 +1,280 @@ +using Fantasy.Entitas; +#if FANTASY_NET +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using Fantasy.Async; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Network.Route; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Timer; +#endif +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Scheduler +{ +#if FANTASY_NET + public struct NetworkMessageUpdate + { + public NetworkMessagingComponent NetworkMessagingComponent; + } + + public class NetworkMessagingComponentAwakeSystem : AwakeSystem + { + protected override void Awake(NetworkMessagingComponent self) + { + var selfScene = self.Scene; + self.TimerComponent = selfScene.TimerComponent; + self.MessageDispatcherComponent = selfScene.MessageDispatcherComponent; + self.AddressableRouteMessageLock = selfScene.CoroutineLockComponent.Create(self.GetType().TypeHandle.Value.ToInt64()); + + self.TimerId = self.TimerComponent.Net.RepeatedTimer(10000, new NetworkMessageUpdate() + { + NetworkMessagingComponent = self + }); + } + } + + public class NetworkMessagingComponentDestroySystem : DestroySystem + { + protected override void Destroy(NetworkMessagingComponent self) + { + if (self.TimerId != 0) + { + self.TimerComponent.Net.Remove(ref self.TimerId); + } + + foreach (var (rpcId, messageSender) in self.RequestCallback.ToDictionary()) + { + self.ReturnMessageSender(rpcId, messageSender); + } + + self.AddressableRouteMessageLock.Dispose(); + + self.RequestCallback.Clear(); + self.TimeoutRouteMessageSenders.Clear(); + self.TimerComponent = null; + self.MessageDispatcherComponent = null; + self.AddressableRouteMessageLock = null; + } + } +#endif + public sealed class NetworkMessagingComponent : Entity + { +#if FANTASY_NET + public long TimerId; + private uint _rpcId; + public CoroutineLock AddressableRouteMessageLock; + public TimerComponent TimerComponent; + public MessageDispatcherComponent MessageDispatcherComponent; + public readonly SortedDictionary RequestCallback = new(); + public readonly Dictionary TimeoutRouteMessageSenders = new(); + + public void SendInnerRoute(long routeId, IRouteMessage message) + { + if (routeId == 0) + { + Log.Error($"SendInnerRoute appId == 0"); + return; + } + + Scene.GetSession(routeId).Send(message, 0, routeId); + } + + internal void SendInnerRoute(long routeId, Type messageType, APackInfo packInfo) + { + if (routeId == 0) + { + Log.Error($"SendInnerRoute routeId == 0"); + return; + } + + Scene.GetSession(routeId).Send(0, routeId, messageType, packInfo); + } + + public void SendInnerRoute(ICollection routeIdCollection, IRouteMessage message) + { + if (routeIdCollection.Count <= 0) + { + Log.Error("SendInnerRoute routeIdCollection.Count <= 0"); + return; + } + + using var processPackInfo = ProcessPackInfo.Create(Scene, message, routeIdCollection.Count); + foreach (var routeId in routeIdCollection) + { + processPackInfo.Set(0, routeId); + Scene.GetSession(routeId).Send(processPackInfo, 0, routeId); + } + } + + public async FTask SendAddressable(long addressableId, IRouteMessage message) + { + await CallAddressable(addressableId, message); + } + + internal async FTask CallInnerRoute(long routeId, Type requestType, APackInfo packInfo) + { + if (routeId == 0) + { + Log.Error($"CallInnerRoute routeId == 0"); + return null; + } + + var rpcId = ++_rpcId; + var session = Scene.GetSession(routeId); + var requestCallback = FTask.Create(false); + RequestCallback.Add(rpcId, MessageSender.Create(rpcId, requestType, requestCallback)); + session.Send(rpcId, routeId, requestType, packInfo); + return await requestCallback; + } + + public async FTask CallInnerRouteBySession(Session session, long routeId, IRouteMessage request) + { + var rpcId = ++_rpcId; + var requestCallback = FTask.Create(false); + RequestCallback.Add(rpcId, MessageSender.Create(rpcId, request, requestCallback)); + session.Send(request, rpcId, routeId); + return await requestCallback; + } + + public async FTask CallInnerRoute(long routeId, IRouteMessage request) + { + if (routeId == 0) + { + Log.Error($"CallInnerRoute routeId == 0"); + return null; + } + + var rpcId = ++_rpcId; + var session = Scene.GetSession(routeId); + var requestCallback = FTask.Create(false); + RequestCallback.Add(rpcId, MessageSender.Create(rpcId, request, requestCallback)); + session.Send(request, rpcId, routeId); + return await requestCallback; + } + + public async FTask CallAddressable(long addressableId, IRouteMessage request) + { + var failCount = 0; + + using (await AddressableRouteMessageLock.Wait(addressableId, "CallAddressable")) + { + var addressableRouteId = await AddressableHelper.GetAddressableRouteId(Scene, addressableId); + + while (true) + { + if (addressableRouteId == 0) + { + addressableRouteId = await AddressableHelper.GetAddressableRouteId(Scene, addressableId); + } + + if (addressableRouteId == 0) + { + return MessageDispatcherComponent.CreateResponse(request.GetType(), InnerErrorCode.ErrNotFoundRoute); + } + + var iRouteResponse = await CallInnerRoute(addressableRouteId, request); + + switch (iRouteResponse.ErrorCode) + { + case InnerErrorCode.ErrNotFoundRoute: + { + if (++failCount > 20) + { + Log.Error($"AddressableComponent.Call failCount > 20 route send message fail, routeId: {addressableRouteId} AddressableMessageComponent:{addressableId}"); + return iRouteResponse; + } + + await TimerComponent.Net.WaitAsync(500); + addressableRouteId = 0; + continue; + } + case InnerErrorCode.ErrRouteTimeout: + { + Log.Error($"CallAddressableRoute ErrorCode.ErrRouteTimeout Error:{iRouteResponse.ErrorCode} Message:{request}"); + return iRouteResponse; + } + default: + { + return iRouteResponse; + } + } + } + } + } + + public void ResponseHandler(uint rpcId, IResponse response) + { + if (!RequestCallback.Remove(rpcId, out var routeMessageSender)) + { + throw new Exception($"not found rpc, response.RpcId:{rpcId} response message: {response.GetType().Name} Process:{Scene.Process.Id} Scene:{Scene.SceneConfigId}"); + } + + ResponseHandler(routeMessageSender, response); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ResponseHandler(MessageSender messageSender, IResponse response) + { + if (response.ErrorCode == InnerErrorCode.ErrRouteTimeout) + { +#if FANTASY_DEVELOP + messageSender.Tcs.SetException(new Exception($"Rpc error: request, 注意RouteId消息超时,请注意查看是否死锁或者没有reply: RouteId: {messageSender.RouteId} {messageSender.Request.ToJson()}, response: {response}")); +#else + messageSender.Tcs.SetException(new Exception($"Rpc error: request, 注意RouteId消息超时,请注意查看是否死锁或者没有reply: RouteId: {messageSender.RouteId} {messageSender.Request}, response: {response}")); +#endif + messageSender.Dispose(); + return; + } + + messageSender.Tcs.SetResult(response); + messageSender.Dispose(); + } + + public void ReturnMessageSender(uint rpcId, MessageSender messageSender) + { + try + { + switch (messageSender.Request) + { + case IRouteMessage iRouteMessage: + { + // IRouteMessage是个特殊的RPC协议、这里不处理就可以了。 + break; + } + case IRequest iRequest: + { + var response = MessageDispatcherComponent.CreateResponse(iRequest.GetType(), InnerErrorCode.ErrRpcFail); + var responseRpcId = messageSender.RpcId; + ResponseHandler(responseRpcId, response); + Log.Warning($"timeout rpcId:{rpcId} responseRpcId:{responseRpcId} {iRequest.ToJson()}"); + break; + } + default: + { + Log.Error(messageSender.Request != null + ? $"Unsupported protocol type {messageSender.Request.GetType()} rpcId:{rpcId}" + : $"Unsupported protocol type:{messageSender.MessageType.FullName} rpcId:{rpcId}"); + RequestCallback.Remove(rpcId); + break; + } + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } +#endif + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta new file mode 100644 index 00000000..415bdd4e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/NetworkMessagingComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2edb273f5cbb94e8082501778cba1427 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs new file mode 100644 index 00000000..7dd2ea3f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs @@ -0,0 +1,60 @@ +using Fantasy.Helper; +using Fantasy.Timer; + +#if FANTASY_NET +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +namespace Fantasy.Scheduler +{ + /// + /// 网络消息更新检查超时。 + /// + public sealed class OnNetworkMessageUpdateCheckTimeout : TimerHandler + { + /// + /// 超时时间(毫秒)。 + /// + private const long Timeout = 40000; + + /// + /// 处理网络消息更新检查超时。 + /// + /// + /// + protected override void Handler(NetworkMessageUpdate self) + { + var timeNow = TimeHelper.Now; + var selfNetworkMessagingComponent = self.NetworkMessagingComponent; + + // 遍历请求回调字典,检查是否有超时的请求,将超时请求添加到超时消息发送列表中。 + + foreach (var (rpcId, value) in selfNetworkMessagingComponent.RequestCallback) + { + if (timeNow < value.CreateTime + Timeout) + { + break; + } + + selfNetworkMessagingComponent.TimeoutRouteMessageSenders.Add(rpcId, value); + } + + // 如果没有超时的请求,直接返回。 + + if (selfNetworkMessagingComponent.TimeoutRouteMessageSenders.Count == 0) + { + return; + } + + // 处理超时的请求,根据请求类型生成相应的响应消息,并进行处理。 + + foreach (var (rpcId, routeMessageSender) in selfNetworkMessagingComponent.TimeoutRouteMessageSenders) + { + selfNetworkMessagingComponent.ReturnMessageSender(rpcId, routeMessageSender); + } + + // 清空超时消息发送列表。 + + selfNetworkMessagingComponent.TimeoutRouteMessageSenders.Clear(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta new file mode 100644 index 00000000..2fc6aaea --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/MessageHelper/OnNetworkMessageUpdateCheckTimeout.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0745c0a5c402e4b7982277a978693d5c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs new file mode 100644 index 00000000..f3c4a549 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs @@ -0,0 +1,286 @@ +using System; +using Fantasy.Network; +using Fantasy.PacketParser.Interface; +#if FANTASY_NET +using Fantasy.Network.Interface; +using Fantasy.Network.Route; +using Fantasy.PacketParser; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.InnerMessage; +#endif + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.Scheduler +{ + /// + /// 提供了一个机制来调度和处理外部网络消息。 + /// +#if FANTASY_UNITY + public sealed class OuterMessageScheduler : ANetworkMessageScheduler + { + public OuterMessageScheduler(Scene scene) : base(scene) { } + + /// + /// 在Unity环境下,处理外部消息的方法。 + /// + /// 网络会话。 + /// 消息类型。 + /// 消息封包信息。 + public override void Scheduler(Session session, APackInfo packInfo) + { + throw new NotSupportedException($"Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } +#endif +#if FANTASY_NET + internal sealed class OuterMessageScheduler(Scene scene) : ANetworkMessageScheduler(scene) + { + private readonly PingResponse _pingResponse = new PingResponse(); + public override void Scheduler(Session session, APackInfo packInfo) + { + HandlerAsync(session, packInfo).Coroutine(); + } + + private async FTask HandlerAsync(Session session, APackInfo packInfo) + { + if (session.IsDisposed) + { + return; + } + + switch (packInfo.OpCodeIdStruct.Protocol) + { + case OpCodeType.OuterPingRequest: + { + // 注意心跳目前只有外网才才会有、内网之间不需要心跳。 + + session.LastReceiveTime = TimeHelper.Now; + _pingResponse.Now = session.LastReceiveTime; + + using (packInfo) + { + session.Send(_pingResponse, packInfo.RpcId); + } + + return; + } + case OpCodeType.OuterMessage: + case OpCodeType.OuterRequest: + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + try + { + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var message = packInfo.Deserialize(messageType); + MessageDispatcherComponent.MessageHandler(session, messageType, message, packInfo.RpcId, packInfo.ProtocolCode); + } + catch (Exception e) + { + Log.Error($"ANetworkMessageScheduler OuterResponse error messageProtocolCode:{packInfo.ProtocolCode} messageType:{messageType} SessionId {session.Id} IsDispose {session.IsDisposed} {e}"); + } + finally + { + packInfo.Dispose(); + } + + return; + } + case OpCodeType.OuterResponse: + { + using (packInfo) + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + NetworkMessagingComponent.ResponseHandler(packInfo.RpcId, (IResponse)packInfo.Deserialize(messageType)); + } + + return; + } + case OpCodeType.OuterAddressableMessage: + { + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var addressableRouteComponent = session.GetComponent(); + + if (addressableRouteComponent == null) + { + throw new Exception("OuterMessageScheduler error session does not have an AddressableRouteComponent component"); + } + + await addressableRouteComponent.Send(messageType, packInfo); + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterAddressableRequest: + { + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var addressableRouteComponent = session.GetComponent(); + + if (addressableRouteComponent == null) + { + throw new Exception("OuterMessageScheduler error session does not have an AddressableRouteComponent component"); + } + + var rpcId = packInfo.RpcId; + var runtimeId = session.RuntimeId; + var response = await addressableRouteComponent.Call(messageType, packInfo); + // session可能已经断开了,所以这里需要判断 + if (session.RuntimeId == runtimeId) + { + session.Send(response, rpcId); + } + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterCustomRouteMessage: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + if (!MessageDispatcherComponent.GetCustomRouteType(packInfoProtocolCode, out var routeType)) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var routeComponent = session.GetComponent(); + + if (routeComponent == null) + { + throw new Exception("OuterMessageScheduler CustomRouteType session does not have an routeComponent component"); + } + + if (!routeComponent.TryGetRouteId(routeType, out var routeId)) + { + throw new Exception($"OuterMessageScheduler RouteComponent cannot find RouteId with RouteType {routeType}"); + } + + NetworkMessagingComponent.SendInnerRoute(routeId, messageType, packInfo); + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + case OpCodeType.OuterCustomRouteRequest: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + var packInfoPackInfoId = packInfo.PackInfoId; + + try + { + if (!MessageDispatcherComponent.GetCustomRouteType(packInfoProtocolCode, out var routeType)) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var messageType = MessageDispatcherComponent.GetOpCodeType(packInfo.ProtocolCode); + + if (messageType == null) + { + throw new Exception($"OuterMessageScheduler error 可能遭受到恶意发包或没有协议定义ProtocolCode ProtocolCode:{packInfo.ProtocolCode}"); + } + + var routeComponent = session.GetComponent(); + + if (routeComponent == null) + { + throw new Exception("OuterMessageScheduler CustomRouteType session does not have an routeComponent component"); + } + + if (!routeComponent.TryGetRouteId(routeType, out var routeId)) + { + throw new Exception($"OuterMessageScheduler RouteComponent cannot find RouteId with RouteType {routeType}"); + } + + var rpcId = packInfo.RpcId; + var runtimeId = session.RuntimeId; + var response = await NetworkMessagingComponent.CallInnerRoute(routeId, messageType, packInfo); + // session可能已经断开了,所以这里需要判断 + if (session.RuntimeId == runtimeId) + { + session.Send(response, rpcId); + } + } + finally + { + if (packInfo.PackInfoId == packInfoPackInfoId) + { + packInfo.Dispose(); + } + } + + return; + } + default: + { + packInfo.Dispose(); + throw new NotSupportedException($"OuterMessageScheduler Received unsupported message protocolCode:{packInfo.ProtocolCode}"); + } + } + } + } +#endif +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta new file mode 100644 index 00000000..2a06b068 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Message/Scheduler/OuterMessageScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 930429df1bd294cd4b38dd138fc43948 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol.meta new file mode 100644 index 00000000..182fffc0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a02133269e172491b86c3e09afa4f7e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception.meta new file mode 100644 index 00000000..8e242437 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 77e3add9ae69f48e2b054f8246914c2e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception/ScanException.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception/ScanException.cs new file mode 100644 index 00000000..43c695a8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception/ScanException.cs @@ -0,0 +1,21 @@ +using System; + +namespace Fantasy.Network +{ + /// + /// 在扫描过程中发生的异常。 + /// + public class ScanException : Exception + { + /// + /// 初始化 类的新实例。 + /// + public ScanException() { } + + /// + /// 使用指定的错误消息初始化 类的新实例。 + /// + /// 错误消息。 + public ScanException(string msg) : base(msg) { } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception/ScanException.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception/ScanException.cs.meta new file mode 100644 index 00000000..5ed0772f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Exception/ScanException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 91ac5b10fc1344aaf9e71ed8eb26ff92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP.meta new file mode 100644 index 00000000..c0d7ff17 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5bf4e2b57147246c6b32a7b458788c5e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs new file mode 100644 index 00000000..5a12369c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs @@ -0,0 +1,100 @@ +#if FANTASY_NET +using System.Net; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Network.Interface; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +#pragma warning disable CS8604 // Possible null reference argument. + +// ReSharper disable PossibleMultipleEnumeration + +namespace Fantasy.Network.HTTP +{ + /// + /// HTTP服务器 + /// + public sealed class HTTPServerNetwork : ANetwork + { + /// + /// 初始化入口 + /// + /// + /// + public void Initialize(NetworkTarget networkTarget, IEnumerable urls) + { + base.Initialize(NetworkType.Server, NetworkProtocolType.HTTP, networkTarget); + + try + { + StartAsync(urls); + } + catch (HttpListenerException e) + { + if (e.ErrorCode == 5) + { + throw new Exception($"CMD管理员中输入: netsh http add urlacl url=http://*:8080/ user=Everyone", e); + } + + Log.Error(e); + } + catch (Exception e) + { + Log.Error(e); + } + } + + private void StartAsync(IEnumerable urls) + { + var builder = WebApplication.CreateBuilder(); + // 配置日志级别为 Warning 或更高 + builder.Logging.ClearProviders(); + builder.Logging.AddConsole(); + builder.Logging.SetMinimumLevel(LogLevel.Warning); + // 将Scene注册到 DI 容器中,传递给控制器 + builder.Services.AddSingleton(Scene); + // 注册Scene同步过滤器 + builder.Services.AddScoped(); + // 注册控制器服务 + var addControllers = builder.Services.AddControllers() + .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; }); + foreach (var assembly in AssemblySystem.ForEachAssembly) + { + addControllers.AddApplicationPart(assembly); + } + + var app = builder.Build(); + // 配置多个监听地址 + foreach (var url in urls) + { + app.Urls.Add(url); + } + + // 启用开发者工具 + if (app.Environment.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + // 路由注册 + app.MapControllers(); + // 开启监听 + app.RunAsync(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} HTTPServer Listen {urls.FirstOrDefault()}"); + } + + /// + /// 移除Channel + /// + /// + /// + public override void RemoveChannel(uint channelId) + { + throw new NotImplementedException(); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta new file mode 100644 index 00000000..0f5c749d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/HTTPServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 31856335ba0fe44a190c792ac8a00591 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/SceneContextFilter.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/SceneContextFilter.cs new file mode 100644 index 00000000..2688bdcf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/SceneContextFilter.cs @@ -0,0 +1,54 @@ +#if FANTASY_NET +using Fantasy.Async; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Fantasy.Network.HTTP; + +/// +/// 让所有实现SceneContextFilter的控制器,都在执行的Scene下执行 +/// +public sealed class SceneContextFilter : IAsyncActionFilter +{ + private readonly Scene _scene; + + /// + /// 构造函数 + /// + /// + public SceneContextFilter(Scene scene) + { + _scene = scene; + } + + /// + /// OnActionExecutionAsync + /// + /// + /// + /// + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var tcs = FTask.Create(); + + _scene.ThreadSynchronizationContext.Post(() => + { + Action().Coroutine(); + }); + + await tcs; + return; + + async FTask Action() + { + try + { + await next(); + } + finally + { + tcs.SetResult(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta new file mode 100644 index 00000000..2f747e48 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/HTTP/SceneContextFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 21bf22052c50e4863a4ca66c0876ee41 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface.meta new file mode 100644 index 00000000..81d84ae8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 88c6dddc716ee427c84ccbd728512576 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/AClientNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/AClientNetwork.cs new file mode 100644 index 00000000..322c8111 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/AClientNetwork.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using Fantasy.Serialize; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + /// + /// 抽象客户端网络基类。 + /// + public abstract class AClientNetwork : ANetwork, INetworkChannel + { + protected bool IsInit; + public Session Session { get; protected set; } + public abstract Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000); + public abstract void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message); + public override void Dispose() + { + IsInit = false; + + if (Session != null) + { + if (!Session.IsDisposed) + { + Session.Dispose(); + } + + Session = null; + } + + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta new file mode 100644 index 00000000..a1d2d54f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/AClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5199ea30d15a6455e90c36094c43d539 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetwork.cs new file mode 100644 index 00000000..fdb85f2f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetwork.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using Fantasy.Entitas; +using Fantasy.PacketParser; +using Fantasy.Scheduler; +using Fantasy.Serialize; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + /// + /// 抽象网络基类。 + /// + public abstract class ANetwork : Entity + { + private long _outerPackInfoId; + private Queue _outerPackInfoPool; + public readonly MemoryStreamBufferPool MemoryStreamBufferPool = new MemoryStreamBufferPool(); + + public NetworkType NetworkType { get; private set; } + public NetworkTarget NetworkTarget { get; private set; } + public NetworkProtocolType NetworkProtocolType { get; private set; } + public ANetworkMessageScheduler NetworkMessageScheduler { get; private set; } + + protected void Initialize(NetworkType networkType, NetworkProtocolType networkProtocolType, NetworkTarget networkTarget) + { + NetworkType = networkType; + NetworkTarget = networkTarget; + NetworkProtocolType = networkProtocolType; +#if FANTASY_NET + if (networkProtocolType == NetworkProtocolType.HTTP) + { + return; + } + if (networkTarget == NetworkTarget.Inner) + { + _innerPackInfoPool = new Queue(); + NetworkMessageScheduler = new InnerMessageScheduler(Scene); + return; + } +#endif + switch (networkType) + { + case NetworkType.Client: + { + _outerPackInfoPool = new Queue(); + NetworkMessageScheduler = new ClientMessageScheduler(Scene); + break; + } +#if FANTASY_NET + case NetworkType.Server: + { + _outerPackInfoPool = new Queue(); + NetworkMessageScheduler = new OuterMessageScheduler(Scene); + break; + } +#endif + } + } + + public abstract void RemoveChannel(uint channelId); + public OuterPackInfo RentOuterPackInfo() + { + if (_outerPackInfoPool.Count == 0) + { + return new OuterPackInfo() + { + PackInfoId = ++_outerPackInfoId + }; + } + + if (!_outerPackInfoPool.TryDequeue(out var outerPackInfo)) + { + return new OuterPackInfo() + { + PackInfoId = ++_outerPackInfoId + }; + } + + outerPackInfo.PackInfoId = ++_outerPackInfoId; + return outerPackInfo; + } + + public void ReturnOuterPackInfo(OuterPackInfo outerPackInfo) + { + if (_outerPackInfoPool.Count > 512) + { + // 池子里最多缓存256个、其实这样设置有点多了、其实用不了512个。 + // 反而设置越大内存会占用越多。 + return; + } + + _outerPackInfoPool.Enqueue(outerPackInfo); + } +#if FANTASY_NET + private long _innerPackInfoId; + private Queue _innerPackInfoPool; + public InnerPackInfo RentInnerPackInfo() + { + if (_innerPackInfoPool.Count == 0) + { + return new InnerPackInfo() + { + PackInfoId = ++_innerPackInfoId + }; + } + + if (!_innerPackInfoPool.TryDequeue(out var innerPackInfo)) + { + return new InnerPackInfo() + { + PackInfoId = ++_innerPackInfoId + }; + } + + innerPackInfo.PackInfoId = ++_innerPackInfoId; + return innerPackInfo; + } + + public void ReturnInnerPackInfo(InnerPackInfo innerPackInfo) + { + if (_innerPackInfoPool.Count > 256) + { + // 池子里最多缓存256个、其实这样设置有点多了、其实用不了256个。 + // 反而设置越大内存会占用越多。 + return; + } + + _innerPackInfoPool.Enqueue(innerPackInfo); + } +#endif + public override void Dispose() + { + NetworkType = NetworkType.None; + NetworkTarget = NetworkTarget.None; + NetworkProtocolType = NetworkProtocolType.None; + MemoryStreamBufferPool.Dispose(); + _outerPackInfoPool?.Clear(); +#if FANTASY_NET + _innerPackInfoPool?.Clear(); +#endif + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetwork.cs.meta new file mode 100644 index 00000000..b6397b25 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66036fdeeb81c43cab7485def9ddefaa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs new file mode 100644 index 00000000..788a235e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs @@ -0,0 +1,55 @@ +#if FANTASY_NET +using System.IO; +using System.Net; +using Fantasy.Serialize; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.Interface +{ + public abstract class ANetworkServerChannel : INetworkChannel + { + /// + /// 获取通道的唯一标识 ID。 + /// + public readonly uint Id; + /// + /// 获取通道的远程终端点。 + /// + public readonly EndPoint RemoteEndPoint; + /// + /// 获取或设置通道所属的场景。 + /// + public Scene Scene { get; protected set; } + /// + /// 获取或设置通道所属的会话。 + /// + public Session Session { get; protected set; } + /// + /// 获取通道是否已经被释放。 + /// + public bool IsDisposed { get; protected set; } + + protected ANetworkServerChannel(ANetwork network, uint id, EndPoint remoteEndPoint) + { + Id = id; + Scene = network.Scene; + RemoteEndPoint = remoteEndPoint; + Session = Session.Create(network.NetworkMessageScheduler, this, network.NetworkTarget); + } + + public virtual void Dispose() + { + IsDisposed = true; + + if (!Session.IsDisposed) + { + Session.Dispose(); + } + } + + public abstract void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta new file mode 100644 index 00000000..395fc6c3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/ANetworkServerChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 014d26c6224c446bfabd518cdb90a331 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/INetworkChannel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/INetworkChannel.cs new file mode 100644 index 00000000..52f341a4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/INetworkChannel.cs @@ -0,0 +1,14 @@ +using System; +using System.IO; +using Fantasy.Serialize; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Network.Interface +{ + public interface INetworkChannel : IDisposable + { + public Session Session { get;} + public bool IsDisposed { get;} + public void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta new file mode 100644 index 00000000..216a6d2b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/Interface/INetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b7c68ff50f634ca394b773b47d51176 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP.meta new file mode 100644 index 00000000..774a5387 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f61404ce7928d45849910cc416c408e1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base.meta new file mode 100644 index 00000000..3b0a9011 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fd62616e1f0334189977f45b5704df1d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/Kcp.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/Kcp.cs new file mode 100644 index 00000000..b425a666 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/Kcp.cs @@ -0,0 +1,626 @@ +#if UNITY_2021_3_OR_NEWER || GODOT +using System; +using System.Threading; +#endif +using static KCP.IKCP; + +#pragma warning disable CS8601 +#pragma warning disable CS8602 +#pragma warning disable CS8625 + +// ReSharper disable IdentifierTypo +// ReSharper disable GrammarMistakeInComment +// ReSharper disable PossibleNullReferenceException +// ReSharper disable ConvertToAutoPropertyWithPrivateSetter + +namespace KCP +{ + /// + /// Kcp + /// + public sealed unsafe class Kcp : IDisposable + { + /// + /// Kcp + /// + private IKCPCB* _kcp; + + /// + /// Output function + /// + private KcpCallback _output; + + /// + /// Buffer + /// + private byte[] _buffer; + + /// + /// Disposed + /// + private int _disposed; + + /// + /// Structure + /// + /// Output + public Kcp(KcpCallback output) : this(0, output) + { + } + + /// + /// Structure + /// + /// ConversationId + /// Output + public Kcp(uint conv, KcpCallback output) + { + _kcp = ikcp_create(conv, ref _buffer); + _output = output; + } + + /// + /// Set + /// + public bool IsSet => _kcp != null; + + /// + /// Conversation id + /// + public uint ConversationId => _kcp->conv; + + /// + /// Maximum transmission unit + /// + public uint MaximumTransmissionUnit => _kcp->mtu; + + /// + /// Maximum segment size + /// + public uint MaximumSegmentSize => _kcp->mss; + + /// + /// Connection state + /// + public int State => _kcp->state; + + /// + /// The sequence number of the first unacknowledged packet + /// + public uint SendUna => _kcp->snd_una; + + /// + /// The sequence number for the next packet to be sent + /// + public uint SendNext => _kcp->snd_nxt; + + /// + /// The sequence number for the next packet expected to be received + /// + public uint ReceiveNext => _kcp->rcv_nxt; + + /// + /// Slow start threshold for congestion control + /// + public uint SlowStartThreshold => _kcp->ssthresh; + + /// + /// Round-trip time variance + /// + public int RxRttval => _kcp->rx_rttval; + + /// + /// Smoothed round-trip time + /// + public int RxSrtt => _kcp->rx_srtt; + + /// + /// Retransmission timeout + /// + public int RxRto => _kcp->rx_rto; + + /// + /// Minimum retransmission timeout + /// + public int RxMinrto => _kcp->rx_minrto; + + /// + /// Send window size + /// + public uint SendWindowSize => _kcp->snd_wnd; + + /// + /// Receive window size + /// + public uint ReceiveWindowSize => _kcp->rcv_wnd; + + /// + /// Remote window size + /// + public uint RemoteWindowSize => _kcp->rmt_wnd; + + /// + /// Congestion window size + /// + public uint CongestionWindowSize => _kcp->cwnd; + + /// + /// Probe variable for fast recovery + /// + public uint Probe => _kcp->probe; + + /// + /// Current timestamp + /// + public uint Current => _kcp->current; + + /// + /// Flush interval + /// + public uint Interval => _kcp->interval; + + /// + /// Timestamp for the next flush + /// + public uint TimestampFlush => _kcp->ts_flush; + + /// + /// Number of retransmissions + /// + public uint Transmissions => _kcp->xmit; + + /// + /// Number of packets in the receive buffer + /// + public uint ReceiveBufferCount => _kcp->nrcv_buf; + + /// + /// Number of packets in the receive queue + /// + public uint ReceiveQueueCount => _kcp->nrcv_que; + + /// + /// Number of packets wait to receive + /// + public uint WaitReceiveCount => _kcp->nrcv_buf + _kcp->nrcv_que; + + /// + /// Number of packets in the send buffer + /// + public uint SendBufferCount => _kcp->nsnd_buf; + + /// + /// Number of packets in the send queue + /// + public uint SendQueueCount => _kcp->nsnd_que; + + /// + /// Number of packets wait to send + /// + public uint WaitSendCount => _kcp->nsnd_buf + _kcp->nsnd_que; + + /// + /// Whether Nagle's algorithm is disabled + /// + public uint NoDelay => _kcp->nodelay; + + /// + /// Whether the KCP connection has been updated + /// + public uint Updated => _kcp->updated; + + /// + /// Timestamp for the next probe + /// + public uint TimestampProbe => _kcp->ts_probe; + + /// + /// Probe wait time + /// + public uint ProbeWait => _kcp->probe_wait; + + /// + /// Incremental increase + /// + public uint Increment => _kcp->incr; + + /// + /// Pointer to the acknowledge list + /// + public uint* AckList => _kcp->acklist; + + /// + /// Count of acknowledges + /// + public uint AckCount => _kcp->ackcount; + + /// + /// Number of acknowledge blocks + /// + public uint AckBlock => _kcp->ackblock; + + /// + /// Buffer + /// + public byte[] Buffer => _buffer; + + /// + /// Fast resend trigger count + /// + public int FastResend => _kcp->fastresend; + + /// + /// Fast resend limit + /// + public int FastResendLimit => _kcp->fastlimit; + + /// + /// Whether congestion control is disabled + /// + public int NoCongestionWindow => _kcp->nocwnd; + + /// + /// Whether stream mode is enabled + /// + public int StreamMode => _kcp->stream; + + /// + /// Output function pointer + /// + public KcpCallback Output => _output; + + /// + /// Dispose + /// + public void Dispose() + { + if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) + return; + ikcp_release(_kcp); + _kcp = null; + _output = null; + _buffer = null; + GC.SuppressFinalize(this); + } + + /// + /// Set output + /// + /// Output + public void SetOutput(KcpCallback output) => _output = output; + + /// + /// Destructure + /// + ~Kcp() => Dispose(); + + /// + /// Send + /// + /// Buffer + /// Sent bytes + public int Send(byte[] buffer) + { + fixed (byte* src = &buffer[0]) + return ikcp_send(_kcp, src, buffer.Length); + } + + /// + /// Send + /// + /// Buffer + /// Length + /// Sent bytes + public int Send(byte[] buffer, int length) + { + fixed (byte* src = &buffer[0]) + return ikcp_send(_kcp, src, length); + } + + /// + /// Send + /// + /// Buffer + /// Offset + /// Length + /// Sent bytes + public int Send(byte[] buffer, int offset, int length) + { + fixed (byte* src = &buffer[offset]) + return ikcp_send(_kcp, src, length); + } + + /// + /// Send + /// + /// Buffer + /// Sent bytes + public int Send(ReadOnlySpan buffer) + { + fixed (byte* src = &buffer[0]) + return ikcp_send(_kcp, src, buffer.Length); + } + + /// + /// Send + /// + /// Buffer + /// Sent bytes + public int Send(ReadOnlyMemory buffer) + { + fixed (byte* src = &buffer.Span[0]) + return ikcp_send(_kcp, src, buffer.Length); + } + + /// + /// Send + /// + /// Buffer + /// Sent bytes + public int Send(ArraySegment buffer) + { + fixed (byte* src = &buffer.Array[buffer.Offset]) + return ikcp_send(_kcp, src, buffer.Count); + } + + /// + /// Send + /// + /// Buffer + /// Length + /// Sent bytes + public int Send(byte* buffer, int length) => ikcp_send(_kcp, buffer, length); + + /// + /// Send + /// + /// Buffer + /// Offset + /// Length + /// Sent bytes + public int Send(byte* buffer, int offset, int length) => ikcp_send(_kcp, buffer + offset, length); + + /// + /// Input + /// + /// Buffer + /// Input bytes + public int Input(byte[] buffer) + { + fixed (byte* src = &buffer[0]) + return ikcp_input(_kcp, src, buffer.Length); + } + + /// + /// Input + /// + /// Buffer + /// Length + /// Input bytes + public int Input(byte[] buffer, int length) + { + fixed (byte* src = &buffer[0]) + return ikcp_input(_kcp, src, length); + } + + /// + /// Input + /// + /// Buffer + /// Offset + /// Length + /// Input bytes + public int Input(byte[] buffer, int offset, int length) + { + fixed (byte* src = &buffer[offset]) + return ikcp_input(_kcp, src, length); + } + + /// + /// Input + /// + /// Buffer + /// Input bytes + public int Input(ReadOnlySpan buffer) + { + fixed (byte* src = &buffer[0]) + return ikcp_input(_kcp, src, buffer.Length); + } + + /// + /// Input + /// + /// Buffer + /// Input bytes + public int Input(ReadOnlyMemory buffer) + { + fixed (byte* src = &buffer.Span[0]) + return ikcp_input(_kcp, src, buffer.Length); + } + + /// + /// Input + /// + /// Buffer + /// Input bytes + public int Input(ArraySegment buffer) + { + fixed (byte* src = &buffer.Array[buffer.Offset]) + return ikcp_input(_kcp, src, buffer.Count); + } + + /// + /// Input + /// + /// Buffer + /// Length + /// Input bytes + public int Input(byte* buffer, int length) => ikcp_input(_kcp, buffer, length); + + /// + /// Input + /// + /// Buffer + /// Offset + /// Length + /// Input bytes + public int Input(byte* buffer, int offset, int length) => ikcp_input(_kcp, buffer + offset, length); + + /// + /// Peek size + /// + /// Peeked size + public int PeekSize() => ikcp_peeksize(_kcp); + + /// + /// Receive + /// + /// Buffer + /// Received bytes + public int Receive(byte[] buffer) + { + fixed (byte* dest = &buffer[0]) + return ikcp_recv(_kcp, dest, buffer.Length); + } + + /// + /// Receive + /// + /// Buffer + /// Length + /// Received bytes + public int Receive(byte[] buffer, int length) + { + fixed (byte* dest = &buffer[0]) + return ikcp_recv(_kcp, dest, length); + } + + /// + /// Receive + /// + /// Buffer + /// Offset + /// Length + /// Received bytes + public int Receive(byte[] buffer, int offset, int length) + { + fixed (byte* dest = &buffer[offset]) + return ikcp_recv(_kcp, dest, length); + } + + /// + /// Receive + /// + /// Buffer + /// Received bytes + public int Receive(Span buffer) + { + fixed (byte* dest = &buffer[0]) + return ikcp_recv(_kcp, dest, buffer.Length); + } + + /// + /// Receive + /// + /// Buffer + /// Received bytes + public int Receive(Memory buffer) + { + fixed (byte* dest = &buffer.Span[0]) + return ikcp_recv(_kcp, dest, buffer.Length); + } + + /// + /// Receive + /// + /// Buffer + /// Received bytes + public int Receive(ArraySegment buffer) + { + fixed (byte* dest = &buffer.Array[buffer.Offset]) + return ikcp_recv(_kcp, dest, buffer.Count); + } + + /// + /// Receive + /// + /// Buffer + /// Length + /// Received bytes + public int Receive(byte* buffer, int length) => ikcp_recv(_kcp, buffer, length); + + /// + /// Receive + /// + /// Buffer + /// Offset + /// Length + /// Received bytes + public int Receive(byte* buffer, int offset, int length) => ikcp_recv(_kcp, buffer + offset, length); + + /// + /// Update + /// + /// Timestamp + public void Update(uint current) => ikcp_update(_kcp, current, _output, _buffer); + + /// + /// Check + /// + /// Timestamp + /// Next flush timestamp + public uint Check(uint current) => ikcp_check(_kcp, current); + + /// + /// Flush + /// + public void Flush() => ikcp_flush(_kcp, _output, _buffer); + + /// + /// Set maximum transmission unit + /// + /// Maximum transmission unit + /// Set + public int SetMtu(int mtu) => ikcp_setmtu(_kcp, mtu, ref _buffer); + + /// + /// Set flush interval + /// + /// Flush interval + public void SetInterval(int interval) => ikcp_interval(_kcp, interval); + + /// + /// Set no delay + /// + /// Whether Nagle's algorithm is disabled + /// Flush interval + /// Fast resend trigger count + /// No congestion window + public void SetNoDelay(int nodelay, int interval, int resend, int nc) => ikcp_nodelay(_kcp, nodelay, interval, resend, nc); + + /// + /// Set window size + /// + /// Send window size + /// Receive window size + public void SetWindowSize(int sndwnd, int rcvwnd) => ikcp_wndsize(_kcp, sndwnd, rcvwnd); + + /// + /// Set fast resend limit + /// + /// Fast resend limit + public void SetFastResendLimit(int fastlimit) => ikcp_fastresendlimit(_kcp, fastlimit); + + /// + /// Set whether stream mode is enabled + /// + /// Whether stream mode is enabled + public void SetStreamMode(int stream) => ikcp_streammode(_kcp, stream); + + /// + /// Set minimum retransmission timeout + /// + /// Minimum retransmission timeout + public void SetMinrto(int minrto) => ikcp_minrto(_kcp, minrto); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta new file mode 100644 index 00000000..f114766f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/Kcp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f5d7dd29b23440a1bcddb58b7bd2a14 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcpc.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcpc.cs new file mode 100644 index 00000000..25758059 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcpc.cs @@ -0,0 +1,1218 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy; +using static KCP.IQUEUEHEAD; +using static KCP.KCPBASIC; + +#pragma warning disable CS8600 +#pragma warning disable CS8602 +#pragma warning disable CS8981 + +// ReSharper disable IdentifierTypo +// ReSharper disable InconsistentNaming +// ReSharper disable ConvertIfStatementToSwitchStatement + +namespace KCP +{ + internal static unsafe class IKCP + { + private static void memcpy(void* dest, void* src, int n) + { + Unsafe.CopyBlockUnaligned(dest, src, (uint)n); + } + + private static void memcpy(void* dest, void* src, uint n) + { + Unsafe.CopyBlockUnaligned(dest, src, n); + } + + private static void* malloc(nint size) => +#if !UNITY_2021_3_OR_NEWER || NET6_0_OR_GREATER + NativeMemory.Alloc((nuint)size); +#else + (void*)Marshal.AllocHGlobal(size); +#endif + + private static void* malloc(nuint size) => +#if !UNITY_2021_3_OR_NEWER || NET6_0_OR_GREATER + NativeMemory.Alloc(size); +#else + (void*)Marshal.AllocHGlobal((nint)size); +#endif + + private static void free(void* ptr) => +#if !UNITY_2021_3_OR_NEWER || NET6_0_OR_GREATER + NativeMemory.Free(ptr); +#else + Marshal.FreeHGlobal((nint)ptr); +#endif + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte* ikcp_encode8u(byte* p, byte c) + { + *p++ = c; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte* ikcp_decode8u(byte* p, byte* c) + { + *c = *p++; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte* ikcp_encode16u(byte* p, ushort w) + { + memcpy(p, &w, 2); + p += 2; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte* ikcp_decode16u(byte* p, ushort* w) + { + memcpy(w, p, 2); + p += 2; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte* ikcp_encode32u(byte* p, uint l) + { + memcpy(p, &l, 4); + p += 4; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static byte* ikcp_decode32u(byte* p, uint* l) + { + memcpy(l, p, 4); + p += 4; + return p; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint _imin_(uint a, uint b) => a <= b ? a : b; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint _imax_(uint a, uint b) => a >= b ? a : b; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint _ibound_(uint lower, uint middle, uint upper) => _imin_(_imax_(lower, middle), upper); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int _iclamp_(int x, uint min, uint max) => x < min ? (int)min : x > max ? (int)max : x; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint _iceilpow2_(uint x) + { + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + x++; + return x; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int _itimediff(uint later, uint earlier) => (int)(later - earlier); + + private static void* ikcp_malloc(nint size) => malloc(size); + + private static void* ikcp_malloc(nuint size) => malloc(size); + + private static void ikcp_free(void* ptr) => free(ptr); + + private static IKCPSEG* ikcp_segment_new(IKCPCB* kcp, int size) => (IKCPSEG*)ikcp_malloc(sizeof(IKCPSEG) + size); + + private static void ikcp_segment_delete(IKCPCB* kcp, IKCPSEG* seg) => ikcp_free(seg); + + private static void ikcp_output(KcpCallback output, byte[] data, int size) + { + if (size == 0) + return; + output(data, ref size); + } + + public static IKCPCB* ikcp_create(uint conv, ref byte[] buffer) + { + var kcp = (IKCPCB*)ikcp_malloc(sizeof(IKCPCB)); + kcp->conv = conv; + kcp->snd_una = 0; + kcp->snd_nxt = 0; + kcp->rcv_nxt = 0; + kcp->ts_probe = 0; + kcp->probe_wait = 0; + kcp->snd_wnd = WND_SND; + kcp->rcv_wnd = WND_RCV; + kcp->rmt_wnd = WND_RCV; + kcp->cwnd = 0; + kcp->incr = 0; + kcp->probe = 0; + kcp->mtu = MTU_DEF; + kcp->mss = kcp->mtu - OVERHEAD; + kcp->stream = 0; + buffer = new byte[REVERSED_HEAD + (kcp->mtu + OVERHEAD) * 3]; + iqueue_init(&kcp->snd_queue); + iqueue_init(&kcp->rcv_queue); + iqueue_init(&kcp->snd_buf); + iqueue_init(&kcp->rcv_buf); + kcp->nrcv_buf = 0; + kcp->nsnd_buf = 0; + kcp->nrcv_que = 0; + kcp->nsnd_que = 0; + kcp->state = 0; + kcp->acklist = null; + kcp->ackblock = 0; + kcp->ackcount = 0; + kcp->rx_srtt = 0; + kcp->rx_rttval = 0; + kcp->rx_rto = (int)RTO_DEF; + kcp->rx_minrto = (int)RTO_MIN; + kcp->current = 0; + kcp->interval = INTERVAL; + kcp->ts_flush = INTERVAL; + kcp->nodelay = 0; + kcp->updated = 0; + kcp->ssthresh = THRESH_INIT; + kcp->fastresend = 0; + kcp->fastlimit = (int)FASTACK_LIMIT; + kcp->nocwnd = 0; + kcp->xmit = 0; + return kcp; + } + + public static void ikcp_release(IKCPCB* kcp) + { + if (kcp != null) + { + IKCPSEG* seg; + while (!iqueue_is_empty(&kcp->snd_buf)) + { + seg = iqueue_entry(kcp->snd_buf.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + while (!iqueue_is_empty(&kcp->rcv_buf)) + { + seg = iqueue_entry(kcp->rcv_buf.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + while (!iqueue_is_empty(&kcp->snd_queue)) + { + seg = iqueue_entry(kcp->snd_queue.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + while (!iqueue_is_empty(&kcp->rcv_queue)) + { + seg = iqueue_entry(kcp->rcv_queue.next); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + + if (kcp->acklist != null) + ikcp_free(kcp->acklist); + kcp->nrcv_buf = 0; + kcp->nsnd_buf = 0; + kcp->nrcv_que = 0; + kcp->nsnd_que = 0; + kcp->ackcount = 0; + kcp->acklist = null; + ikcp_free(kcp); + } + } + + public static int ikcp_recv(IKCPCB* kcp, byte* buffer, int len) + { + if (iqueue_is_empty(&kcp->rcv_queue)) + return -1; + var peeksize = ikcp_peeksize_internal(kcp); + if (peeksize < 0) + return -2; + int recover; + IQUEUEHEAD* p; + IKCPSEG* seg; + if (len < 0) + { + len = -len; + if (peeksize > len) + return -3; + recover = kcp->nrcv_que >= kcp->rcv_wnd ? 1 : 0; + p = kcp->rcv_queue.next; + for (len = 0; p != &kcp->rcv_queue;) + { + seg = iqueue_entry(p); + p = p->next; + if (buffer != null) + { + memcpy(buffer, seg->data, seg->len); + buffer += seg->len; + } + + len += (int)seg->len; + var fragment = (int)seg->frg; + if (fragment == 0) + break; + } + } + else + { + if (peeksize > len) + return -3; + recover = kcp->nrcv_que >= kcp->rcv_wnd ? 1 : 0; + p = kcp->rcv_queue.next; + for (len = 0; p != &kcp->rcv_queue;) + { + seg = iqueue_entry(p); + p = p->next; + if (buffer != null) + { + memcpy(buffer, seg->data, seg->len); + buffer += seg->len; + } + + len += (int)seg->len; + var fragment = (int)seg->frg; + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + kcp->nrcv_que--; + if (fragment == 0) + break; + } + } + + while (!iqueue_is_empty(&kcp->rcv_buf)) + { + seg = iqueue_entry(kcp->rcv_buf.next); + if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) + { + iqueue_del(&seg->node); + kcp->nrcv_buf--; + iqueue_add_tail(&seg->node, &kcp->rcv_queue); + kcp->nrcv_que++; + kcp->rcv_nxt++; + } + else + { + break; + } + } + + if (kcp->nrcv_que < kcp->rcv_wnd && recover != 0) + kcp->probe |= ASK_TELL; + return len; + } + + public static int ikcp_peeksize(IKCPCB* kcp) => iqueue_is_empty(&kcp->rcv_queue) ? -1 : ikcp_peeksize_internal(kcp); + + private static int ikcp_peeksize_internal(IKCPCB* kcp) + { + var seg = iqueue_entry(kcp->rcv_queue.next); + if (seg->frg == 0) + return (int)seg->len; + if (kcp->nrcv_que < seg->frg + 1) + return -1; + IQUEUEHEAD* p; + var length = 0; + for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) + { + seg = iqueue_entry(p); + length += (int)seg->len; + if (seg->frg == 0) + break; + } + + return length; + } + + public static int ikcp_send(IKCPCB* kcp, byte* buffer, int len) + { + if (len < 0) + return -1; + IKCPSEG* seg; + var sent = 0; + if (kcp->stream != 0) + { + if (!iqueue_is_empty(&kcp->snd_queue)) + { + var old = iqueue_entry(kcp->snd_queue.prev); + if (old->len < kcp->mss) + { + var capacity = (int)kcp->mss - (int)old->len; + var extend = len < capacity ? len : capacity; + seg = ikcp_segment_new(kcp, (int)old->len + extend); + iqueue_add_tail(&seg->node, &kcp->snd_queue); + memcpy(seg->data, old->data, old->len); + if (buffer != null) + { + memcpy(seg->data + old->len, buffer, extend); + buffer += extend; + } + + seg->len = old->len + (uint)extend; + seg->frg = 0; + len -= extend; + iqueue_del_init(&old->node); + ikcp_segment_delete(kcp, old); + sent = extend; + } + } + + if (len <= 0) + return sent; + int count; + if (len <= (int)kcp->mss) + { + count = 1; + } + else + { + count = (int)((len + kcp->mss - 1) / kcp->mss); + if (count >= (int)kcp->rcv_wnd) + return sent > 0 ? sent : -2; + if (count == 0) + count = 1; + } + + int i; + for (i = 0; i < count; ++i) + { + var size = len > (int)kcp->mss ? (int)kcp->mss : len; + seg = ikcp_segment_new(kcp, size); + if (buffer != null && len > 0) + memcpy(seg->data, buffer, size); + seg->len = (uint)size; + seg->frg = 0; + iqueue_init(&seg->node); + iqueue_add_tail(&seg->node, &kcp->snd_queue); + kcp->nsnd_que++; + if (buffer != null) + buffer += size; + len -= size; + sent += size; + } + } + else + { + int count; + if (len <= (int)kcp->mss) + { + count = 1; + } + else + { + count = (int)((len + kcp->mss - 1) / kcp->mss); + if (count > FRG_LIMIT || count >= (int)kcp->rcv_wnd) + return -2; + if (count == 0) + count = 1; + } + + int i; + for (i = 0; i < count; ++i) + { + var size = len > (int)kcp->mss ? (int)kcp->mss : len; + seg = ikcp_segment_new(kcp, size); + if (buffer != null && len > 0) + memcpy(seg->data, buffer, size); + seg->len = (uint)size; + seg->frg = (uint)(count - i - 1); + iqueue_init(&seg->node); + iqueue_add_tail(&seg->node, &kcp->snd_queue); + kcp->nsnd_que++; + if (buffer != null) + buffer += size; + len -= size; + sent += size; + } + } + + return sent; + } + + private static void ikcp_update_ack(IKCPCB* kcp, int rtt) + { + if (kcp->rx_srtt == 0) + { + kcp->rx_srtt = rtt; + kcp->rx_rttval = rtt / 2; + } + else + { + var delta = rtt - kcp->rx_srtt; + if (delta < 0) + delta = -delta; + kcp->rx_rttval = (3 * kcp->rx_rttval + delta) / 4; + kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8; + if (kcp->rx_srtt < 1) + kcp->rx_srtt = 1; + } + + var rto = (int)(kcp->rx_srtt + _imax_(kcp->interval, (uint)(4 * kcp->rx_rttval))); + kcp->rx_rto = (int)_ibound_((uint)kcp->rx_minrto, (uint)rto, RTO_MAX); + } + + private static void ikcp_shrink_buf(IKCPCB* kcp) + { + var p = kcp->snd_buf.next; + if (p != &kcp->snd_buf) + { + var seg = iqueue_entry(p); + kcp->snd_una = seg->sn; + } + else + { + kcp->snd_una = kcp->snd_nxt; + } + } + + private static void ikcp_parse_ack(IKCPCB* kcp, uint sn) + { + if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) + return; + IQUEUEHEAD* p, next; + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) + { + var seg = iqueue_entry(p); + next = p->next; + if (sn == seg->sn) + { + iqueue_del(p); + ikcp_segment_delete(kcp, seg); + kcp->nsnd_buf--; + break; + } + + if (_itimediff(sn, seg->sn) < 0) + break; + } + } + + private static void ikcp_parse_una(IKCPCB* kcp, uint una) + { + IQUEUEHEAD* p, next; + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) + { + var seg = iqueue_entry(p); + next = p->next; + if (_itimediff(una, seg->sn) > 0) + { + iqueue_del(p); + ikcp_segment_delete(kcp, seg); + kcp->nsnd_buf--; + } + else + { + break; + } + } + } + + private static void ikcp_parse_fastack(IKCPCB* kcp, uint sn, uint ts) + { + if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) + return; + IQUEUEHEAD* p, next; + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) + { + var seg = iqueue_entry(p); + next = p->next; + if (_itimediff(sn, seg->sn) < 0) + break; + if (sn != seg->sn) + { +#if KCP_FASTACK_CONSERVE + seg->fastack++; +#else + if (_itimediff(ts, seg->ts) >= 0) + seg->fastack++; +#endif + } + } + } + + private static int ikcp_ack_push(IKCPCB* kcp, uint sn, uint ts) + { + var newsize = kcp->ackcount + 1; + if (newsize > kcp->ackblock) + { + var newblock = newsize <= 8 ? 8 : _iceilpow2_(newsize); + var acklist = (uint*)ikcp_malloc(newblock << 3); + if (kcp->acklist != null) + { + uint x; + for (x = 0; x < kcp->ackcount; ++x) + { + acklist[x * 2] = kcp->acklist[x * 2]; + acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1]; + } + + ikcp_free(kcp->acklist); + } + + kcp->acklist = acklist; + kcp->ackblock = newblock; + } + + var ptr = &kcp->acklist[kcp->ackcount * 2]; + ptr[0] = sn; + ptr[1] = ts; + kcp->ackcount++; + return 0; + } + + private static void ikcp_ack_get(IKCPCB* kcp, int p, uint* sn, uint* ts) + { + if (sn != null) + sn[0] = kcp->acklist[p * 2]; + if (ts != null) + ts[0] = kcp->acklist[p * 2 + 1]; + } + + private static void ikcp_parse_data(IKCPCB* kcp, IKCPSEG* newseg) + { + var sn = newseg->sn; + if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 || _itimediff(sn, kcp->rcv_nxt) < 0) + { + ikcp_segment_delete(kcp, newseg); + return; + } + + IQUEUEHEAD* p, prev; + var repeat = 0; + for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) + { + var seg = iqueue_entry(p); + prev = p->prev; + if (seg->sn == sn) + { + repeat = 1; + break; + } + + if (_itimediff(sn, seg->sn) > 0) + break; + } + + if (repeat == 0) + { + iqueue_init(&newseg->node); + iqueue_add(&newseg->node, p); + kcp->nrcv_buf++; + } + else + { + ikcp_segment_delete(kcp, newseg); + } + + while (!iqueue_is_empty(&kcp->rcv_buf)) + { + var seg = iqueue_entry(kcp->rcv_buf.next); + if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) + { + iqueue_del(&seg->node); + kcp->nrcv_buf--; + iqueue_add_tail(&seg->node, &kcp->rcv_queue); + kcp->nrcv_que++; + kcp->rcv_nxt++; + } + else + { + break; + } + } + } + + public static int ikcp_input(IKCPCB* kcp, byte* data, int size) + { + if (data == null || size < (int)OVERHEAD) + return -1; + var prev_una = kcp->snd_una; + uint maxack = 0, latest_ts = 0; + var flag = 0; + while (true) + { + uint ts, sn, len, una, conv; + ushort wnd; + byte cmd, frg; + if (size < (int)OVERHEAD) + break; + data = ikcp_decode32u(data, &conv); + if (conv != kcp->conv) + return -1; + data = ikcp_decode8u(data, &cmd); + data = ikcp_decode8u(data, &frg); + data = ikcp_decode16u(data, &wnd); + data = ikcp_decode32u(data, &ts); + data = ikcp_decode32u(data, &sn); + data = ikcp_decode32u(data, &una); + data = ikcp_decode32u(data, &len); + size -= (int)OVERHEAD; + if (size < len || (int)len < 0) + return -2; + if (cmd != CMD_PUSH && cmd != CMD_ACK && cmd != CMD_WASK && cmd != CMD_WINS) + return -3; + kcp->rmt_wnd = wnd; + ikcp_parse_una(kcp, una); + ikcp_shrink_buf(kcp); + if (cmd == CMD_ACK) + { + if (_itimediff(kcp->current, ts) >= 0) + ikcp_update_ack(kcp, _itimediff(kcp->current, ts)); + ikcp_parse_ack(kcp, sn); + ikcp_shrink_buf(kcp); + if (flag == 0) + { + flag = 1; + maxack = sn; + latest_ts = ts; + } + else + { + if (_itimediff(sn, maxack) > 0) + { +#if KCP_FASTACK_CONSERVE + maxack = sn; + latest_ts = ts; +#else + if (_itimediff(ts, latest_ts) > 0) + { + maxack = sn; + latest_ts = ts; + } +#endif + } + } + } + else if (cmd == CMD_PUSH) + { + if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) + { + if (ikcp_ack_push(kcp, sn, ts) != 0) + return -4; + if (_itimediff(sn, kcp->rcv_nxt) >= 0) + { + var seg = ikcp_segment_new(kcp, (int)len); + seg->conv = conv; + seg->cmd = cmd; + seg->frg = frg; + seg->wnd = wnd; + seg->ts = ts; + seg->sn = sn; + seg->una = una; + seg->len = len; + if (len > 0) + memcpy(seg->data, data, len); + ikcp_parse_data(kcp, seg); + } + } + } + else if (cmd == CMD_WASK) + { + kcp->probe |= ASK_TELL; + } + else if (cmd != CMD_WINS) + { + return -3; + } + + data += len; + size -= (int)len; + } + + if (flag != 0) + ikcp_parse_fastack(kcp, maxack, latest_ts); + if (_itimediff(kcp->snd_una, prev_una) > 0) + { + if (kcp->cwnd < kcp->rmt_wnd) + { + var mss = kcp->mss; + if (kcp->cwnd < kcp->ssthresh) + { + kcp->cwnd++; + kcp->incr += mss; + } + else + { + if (kcp->incr < mss) + kcp->incr = mss; + kcp->incr += mss * mss / kcp->incr + mss / 16; + if ((kcp->cwnd + 1) * mss <= kcp->incr) + kcp->cwnd = (kcp->incr + mss - 1) / (mss > 0 ? mss : 1); + } + + if (kcp->cwnd > kcp->rmt_wnd) + { + kcp->cwnd = kcp->rmt_wnd; + kcp->incr = kcp->rmt_wnd * mss; + } + } + } + + return 0; + } + + private static byte* ikcp_encode_seg(byte* ptr, IKCPSEG* seg) + { + ptr = ikcp_encode32u(ptr, seg->conv); + ptr = ikcp_encode8u(ptr, (byte)seg->cmd); + ptr = ikcp_encode8u(ptr, (byte)seg->frg); + ptr = ikcp_encode16u(ptr, (ushort)seg->wnd); + ptr = ikcp_encode32u(ptr, seg->ts); + ptr = ikcp_encode32u(ptr, seg->sn); + ptr = ikcp_encode32u(ptr, seg->una); + ptr = ikcp_encode32u(ptr, seg->len); + return ptr; + } + + private static int ikcp_wnd_unused(IKCPCB* kcp) => kcp->nrcv_que < kcp->rcv_wnd ? (int)(kcp->rcv_wnd - kcp->nrcv_que) : 0; + + public static void ikcp_flush(IKCPCB* kcp, KcpCallback output, byte[] bytes) + { + if (kcp->updated == 0) + return; + ikcp_flush_internal(kcp, output, bytes); + } + + private static void ikcp_flush_internal(IKCPCB* kcp, KcpCallback output, byte[] bytes) + { + var current = kcp->current; + fixed (byte* buffer = &bytes[REVERSED_HEAD]) + { + var ptr = buffer; + int size, i; + IQUEUEHEAD* p; + var change = 0; + var lost = 0; + IKCPSEG seg; + seg.conv = kcp->conv; + seg.cmd = CMD_ACK; + seg.frg = 0; + seg.wnd = (uint)ikcp_wnd_unused(kcp); + seg.una = kcp->rcv_nxt; + seg.len = 0; + seg.sn = 0; + seg.ts = 0; + var count = (int)kcp->ackcount; + for (i = 0; i < count; ++i) + { + size = (int)(ptr - buffer); + if (size + (int)OVERHEAD > (int)kcp->mtu) + { + ikcp_output(output, bytes, size); + ptr = buffer; + } + + ikcp_ack_get(kcp, i, &seg.sn, &seg.ts); + ptr = ikcp_encode_seg(ptr, &seg); + } + + kcp->ackcount = 0; + if (kcp->rmt_wnd == 0) + { + if (kcp->probe_wait == 0) + { + kcp->probe_wait = PROBE_INIT; + kcp->ts_probe = kcp->current + kcp->probe_wait; + } + else + { + if (_itimediff(kcp->current, kcp->ts_probe) >= 0) + { + if (kcp->probe_wait < PROBE_INIT) + kcp->probe_wait = PROBE_INIT; + kcp->probe_wait += kcp->probe_wait / 2; + if (kcp->probe_wait > PROBE_LIMIT) + kcp->probe_wait = PROBE_LIMIT; + kcp->ts_probe = kcp->current + kcp->probe_wait; + kcp->probe |= ASK_SEND; + } + } + } + else + { + kcp->ts_probe = 0; + kcp->probe_wait = 0; + } + + if ((kcp->probe != 0) & (ASK_SEND != 0)) + { + seg.cmd = CMD_WASK; + size = (int)(ptr - buffer); + if (size + (int)OVERHEAD > (int)kcp->mtu) + { + ikcp_output(output, bytes, size); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, &seg); + } + + if ((kcp->probe != 0) & (ASK_TELL != 0)) + { + seg.cmd = CMD_WINS; + size = (int)(ptr - buffer); + if (size + (int)OVERHEAD > (int)kcp->mtu) + { + ikcp_output(output, bytes, size); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, &seg); + } + + kcp->probe = 0; + var cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd); + if (kcp->nocwnd == 0) + cwnd = _imin_(kcp->cwnd, cwnd); + while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) + { + if (iqueue_is_empty(&kcp->snd_queue)) + break; + var newseg = iqueue_entry(kcp->snd_queue.next); + iqueue_del(&newseg->node); + iqueue_add_tail(&newseg->node, &kcp->snd_buf); + kcp->nsnd_que--; + kcp->nsnd_buf++; + newseg->conv = kcp->conv; + newseg->cmd = CMD_PUSH; + newseg->wnd = seg.wnd; + newseg->ts = current; + newseg->sn = kcp->snd_nxt++; + newseg->una = kcp->rcv_nxt; + newseg->resendts = current; + newseg->rto = (uint)kcp->rx_rto; + newseg->fastack = 0; + newseg->xmit = 0; + } + + var resent = kcp->fastresend > 0 ? (uint)kcp->fastresend : 4294967295; + if (kcp->nodelay == 0) + { + var rtomin = (uint)(kcp->rx_rto >> 3); + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) + { + var segment = iqueue_entry(p); + var needsend = 0; + if (segment->xmit == 0) + { + needsend = 1; + segment->xmit++; + segment->rto = (uint)kcp->rx_rto; + segment->resendts = current + segment->rto + rtomin; + } + else if (_itimediff(current, segment->resendts) >= 0) + { + needsend = 1; + segment->xmit++; + kcp->xmit++; + segment->rto += _imax_(segment->rto, (uint)kcp->rx_rto); + segment->resendts = current + segment->rto; + lost = 1; + } + else if (segment->fastack >= resent) + { + if ((int)segment->xmit <= kcp->fastlimit || kcp->fastlimit == 0) + { + needsend = 1; + segment->xmit++; + segment->fastack = 0; + segment->resendts = current + segment->rto; + change++; + } + } + + if (needsend != 0) + { + segment->ts = current; + segment->wnd = seg.wnd; + segment->una = kcp->rcv_nxt; + size = (int)(ptr - buffer); + var need = (int)(OVERHEAD + segment->len); + if (size + need > (int)kcp->mtu) + { + ikcp_output(output, bytes, size); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, segment); + if (segment->len > 0) + { + memcpy(ptr, segment->data, segment->len); + ptr += segment->len; + } + + if (segment->xmit >= DEADLINK) + kcp->state = -1; + } + } + } + else if (kcp->nodelay == 1) + { + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) + { + var segment = iqueue_entry(p); + var needsend = 0; + if (segment->xmit == 0) + { + needsend = 1; + segment->xmit++; + segment->rto = (uint)kcp->rx_rto; + segment->resendts = current + segment->rto; + } + else if (_itimediff(current, segment->resendts) >= 0) + { + needsend = 1; + segment->xmit++; + kcp->xmit++; + var step = (int)segment->rto; + segment->rto += (uint)(step / 2); + segment->resendts = current + segment->rto; + lost = 1; + } + else if (segment->fastack >= resent) + { + if ((int)segment->xmit <= kcp->fastlimit || kcp->fastlimit == 0) + { + needsend = 1; + segment->xmit++; + segment->fastack = 0; + segment->resendts = current + segment->rto; + change++; + } + } + + if (needsend != 0) + { + segment->ts = current; + segment->wnd = seg.wnd; + segment->una = kcp->rcv_nxt; + size = (int)(ptr - buffer); + var need = (int)(OVERHEAD + segment->len); + if (size + need > (int)kcp->mtu) + { + ikcp_output(output, bytes, size); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, segment); + if (segment->len > 0) + { + memcpy(ptr, segment->data, segment->len); + ptr += segment->len; + } + + if (segment->xmit >= DEADLINK) + kcp->state = -1; + } + } + } + else + { + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) + { + var segment = iqueue_entry(p); + var needsend = 0; + if (segment->xmit == 0) + { + needsend = 1; + segment->xmit++; + segment->rto = (uint)kcp->rx_rto; + segment->resendts = current + segment->rto; + } + else if (_itimediff(current, segment->resendts) >= 0) + { + needsend = 1; + segment->xmit++; + kcp->xmit++; + var step = (int)segment->rto; + segment->rto += (uint)(step / 2); + segment->resendts = current + segment->rto; + lost = 1; + } + else if (segment->fastack >= resent) + { + if ((int)segment->xmit <= kcp->fastlimit || kcp->fastlimit == 0) + { + needsend = 1; + segment->xmit++; + segment->fastack = 0; + segment->resendts = current + segment->rto; + change++; + } + } + + if (needsend != 0) + { + segment->ts = current; + segment->wnd = seg.wnd; + segment->una = kcp->rcv_nxt; + size = (int)(ptr - buffer); + var need = (int)(OVERHEAD + segment->len); + if (size + need > (int)kcp->mtu) + { + ikcp_output(output, bytes, size); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, segment); + if (segment->len > 0) + { + memcpy(ptr, segment->data, segment->len); + ptr += segment->len; + } + + if (segment->xmit >= DEADLINK) + kcp->state = -1; + } + } + } + + size = (int)(ptr - buffer); + if (size > 0) + ikcp_output(output, bytes, size); + if (change != 0) + { + var inflight = kcp->snd_nxt - kcp->snd_una; + kcp->ssthresh = inflight / 2; + if (kcp->ssthresh < THRESH_MIN) + kcp->ssthresh = THRESH_MIN; + kcp->cwnd = kcp->ssthresh + resent; + kcp->incr = kcp->cwnd * kcp->mss; + } + + if (lost != 0) + { + kcp->ssthresh = cwnd / 2; + if (kcp->ssthresh < THRESH_MIN) + kcp->ssthresh = THRESH_MIN; + kcp->cwnd = 1; + kcp->incr = kcp->mss; + } + + if (kcp->cwnd < 1) + { + kcp->cwnd = 1; + kcp->incr = kcp->mss; + } + } + } + + public static void ikcp_update(IKCPCB* kcp, uint current, KcpCallback output, byte[] bytes) + { + kcp->current = current; + if (kcp->updated == 0) + { + kcp->updated = 1; + kcp->ts_flush = kcp->current; + } + + var slap = _itimediff(kcp->current, kcp->ts_flush); + if (slap >= 10000 || slap < -10000) + { + kcp->ts_flush = kcp->current; + slap = 0; + } + + if (slap >= 0) + { + kcp->ts_flush += kcp->interval; + if (_itimediff(kcp->current, kcp->ts_flush) >= 0) + kcp->ts_flush = kcp->current + kcp->interval; + ikcp_flush_internal(kcp, output, bytes); + } + } + + public static uint ikcp_check(IKCPCB* kcp, uint current) + { + if (kcp->updated == 0) + return current; + var ts_flush = kcp->ts_flush; + if (_itimediff(current, ts_flush) >= 10000 || _itimediff(current, ts_flush) < -10000) + ts_flush = current; + if (_itimediff(current, ts_flush) >= 0) + return current; + var tm_packet = 2147483647; + var tm_flush = _itimediff(ts_flush, current); + IQUEUEHEAD* p; + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) + { + var seg = iqueue_entry(p); + var diff = _itimediff(seg->resendts, current); + if (diff <= 0) + return current; + if (diff < tm_packet) + tm_packet = diff; + } + + var minimal = (uint)(tm_packet < tm_flush ? tm_packet : tm_flush); + if (minimal >= kcp->interval) + minimal = kcp->interval; + return current + minimal; + } + + public static int ikcp_setmtu(IKCPCB* kcp, int mtu, ref byte[] buffer) + { + if (kcp->mtu == (uint)mtu) + return 0; + if (mtu < (int)OVERHEAD) + return -1; + buffer = new byte[REVERSED_HEAD + (mtu + OVERHEAD) * 3]; + kcp->mtu = (uint)mtu; + kcp->mss = kcp->mtu - OVERHEAD; + return 0; + } + + public static void ikcp_interval(IKCPCB* kcp, int interval) + { + interval = _iclamp_(interval, INTERVAL_MIN, INTERVAL_LIMIT); + kcp->interval = (uint)interval; + } + + public static void ikcp_nodelay(IKCPCB* kcp, int nodelay, int interval, int resend, int nc) + { + nodelay = _iclamp_(nodelay, NODELAY_MIN, NODELAY_LIMIT); + kcp->nodelay = (uint)nodelay; + if (nodelay != 0) + kcp->rx_minrto = (int)RTO_NDL; + else + kcp->rx_minrto = (int)RTO_MIN; + interval = _iclamp_(interval, INTERVAL_MIN, INTERVAL_LIMIT); + kcp->interval = (uint)interval; + resend = _iclamp_(resend, 0, 4294967295); + kcp->fastresend = resend; + kcp->nocwnd = nc == 1 ? 1 : 0; + } + + public static void ikcp_wndsize(IKCPCB* kcp, int sndwnd, int rcvwnd) + { + sndwnd = _iclamp_(sndwnd, WND_SND, 2147483647); + rcvwnd = _iclamp_(rcvwnd, WND_RCV, 2147483647); + kcp->snd_wnd = (uint)sndwnd; + kcp->rcv_wnd = (uint)rcvwnd; + } + + public static void ikcp_fastresendlimit(IKCPCB* kcp, int fastlimit) + { + fastlimit = _iclamp_(fastlimit, FASTACK_MIN, FASTACK_LIMIT); + kcp->fastlimit = fastlimit; + } + + public static void ikcp_streammode(IKCPCB* kcp, int stream) => kcp->stream = stream == 1 ? 1 : 0; + + public static void ikcp_minrto(IKCPCB* kcp, int minrto) + { + minrto = _iclamp_(minrto, INTERVAL_MIN, RTO_MAX); + kcp->rx_minrto = minrto; + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcpc.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcpc.cs.meta new file mode 100644 index 00000000..05781927 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcpc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b0ee69cc284b4c52b9d0f55e73d8d5c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcph.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcph.cs new file mode 100644 index 00000000..ebd5cc6a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcph.cs @@ -0,0 +1,159 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +#pragma warning disable CS1591 +#pragma warning disable CS8981 + +// ReSharper disable IdentifierTypo +// ReSharper disable InconsistentNaming + +namespace KCP +{ + public delegate void KcpCallback(byte[] buffer, ref int length); + + internal unsafe struct IQUEUEHEAD + { + public IQUEUEHEAD* next; + public IQUEUEHEAD* prev; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_init(IQUEUEHEAD* ptr) + { + ptr->next = ptr; + ptr->prev = ptr; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IKCPSEG* iqueue_entry(IQUEUEHEAD* ptr) => (IKCPSEG*)(byte*)(IKCPSEG*)ptr; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool iqueue_is_empty(IQUEUEHEAD* entry) => entry == entry->next; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_del(IQUEUEHEAD* entry) + { + entry->next->prev = entry->prev; + entry->prev->next = entry->next; + entry->next = null; + entry->prev = null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_del_init(IQUEUEHEAD* entry) + { + iqueue_del(entry); + iqueue_init(entry); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_add(IQUEUEHEAD* node, IQUEUEHEAD* head) + { + node->prev = head; + node->next = head->next; + head->next->prev = node; + head->next = node; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void iqueue_add_tail(IQUEUEHEAD* node, IQUEUEHEAD* head) + { + node->prev = head->prev; + node->next = head; + head->prev->next = node; + head->prev = node; + } + } + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IKCPSEG + { + public IQUEUEHEAD node; + public uint conv; + public uint cmd; + public uint frg; + public uint wnd; + public uint ts; + public uint sn; + public uint una; + public uint len; + public uint resendts; + public uint rto; + public uint fastack; + public uint xmit; + public fixed byte data[1]; + } + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct IKCPCB + { + public uint conv, mtu, mss; + public int state; + public uint snd_una, snd_nxt, rcv_nxt; + public uint ssthresh; + public int rx_rttval, rx_srtt, rx_rto, rx_minrto; + public uint snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe; + public uint current, interval, ts_flush, xmit; + public uint nrcv_buf, nsnd_buf; + public uint nrcv_que, nsnd_que; + public uint nodelay, updated; + public uint ts_probe, probe_wait; + public uint incr; + public IQUEUEHEAD snd_queue; + public IQUEUEHEAD rcv_queue; + public IQUEUEHEAD snd_buf; + public IQUEUEHEAD rcv_buf; + public uint* acklist; + public uint ackcount; + public uint ackblock; + public int fastresend; + public int fastlimit; + public int nocwnd, stream; + } + + public static class KCPBASIC + { + public const uint RTO_NDL = 30; + public const uint RTO_MIN = 100; + public const uint RTO_DEF = 200; + public const uint RTO_MAX = 60000; + public const uint CMD_PUSH = 81; + public const uint CMD_ACK = 82; + public const uint CMD_WASK = 83; + public const uint CMD_WINS = 84; + public const uint ASK_SEND = 1; + public const uint ASK_TELL = 2; + public const uint WND_SND = 32; + public const uint WND_RCV = 128; + public const uint MTU_DEF = 1400; + public const uint ACK_FAST = 3; + public const uint INTERVAL = 100; + public const uint INTERVAL_MIN = 1; + public const uint INTERVAL_LIMIT = 5000; + public const uint OVERHEAD = 24; + public const uint DEADLINK = 20; + public const uint THRESH_INIT = 2; + public const uint THRESH_MIN = 2; + public const uint PROBE_INIT = 7000; + public const uint PROBE_LIMIT = 120000; + public const uint FRG_LIMIT = 255; + public const uint NODELAY_MIN = 0; + public const uint NODELAY_LIMIT = 2; + public const uint FASTACK_MIN = 0; + public const uint FASTACK_LIMIT = 5; + public const uint OUTPUT = 1; + public const uint INPUT = 2; + public const uint SEND = 4; + public const uint RECV = 8; + public const uint IN_DATA = 16; + public const uint IN_ACK = 32; + public const uint IN_PROBE = 64; + public const uint IN_WINS = 128; + public const uint OUT_DATA = 256; + public const uint OUT_ACK = 512; + public const uint OUT_PROBE = 1024; + public const uint OUT_WINS = 2048; + + // TODO: remove it if not needed + public const uint REVERSED_HEAD = 5; + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcph.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcph.cs.meta new file mode 100644 index 00000000..30dbc21e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Base/ikcph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 89a1db82f89dc4369b9b3478cd2d33c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client.meta new file mode 100644 index 00000000..1004987d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a04e3efb5ed984e1aac1e1b7da7cd876 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs new file mode 100644 index 00000000..de5ed67a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs @@ -0,0 +1,688 @@ +#if !FANTASY_WEBGL +using System; +using System.Buffers; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Threading; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +using KCP; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable PossibleNullReferenceException +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +namespace Fantasy.Network.KCP +{ + public sealed class KCPClientNetworkUpdateSystem : UpdateSystem + { + protected override void Update(KCPClientNetwork self) + { + self.CheckUpdate(); + } + } + public sealed class KCPClientNetwork : AClientNetwork + { + private Kcp _kcp; + private Socket _socket; + private int _maxSndWnd; + private long _startTime; + private bool _isConnected; + private bool _isDisconnect; + private uint _updateMinTime; + private bool _isInnerDispose; + private long _connectTimeoutId; + private bool _allowWraparound = true; + private IPEndPoint _remoteAddress; + private BufferPacketParser _packetParser; + private readonly Pipe _pipe = new Pipe(); + private readonly byte[] _sendBuff = new byte[5]; + private readonly byte[] _receiveBuffer = new byte[Packet.PacketBodyMaxLength + 20]; + private readonly List _updateTimeOutTime = new List(); + private readonly SortedSet _updateTimer = new SortedSet(); + private readonly SocketAsyncEventArgs _connectEventArgs = new SocketAsyncEventArgs(); + private readonly Queue _messageCache = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); +#if FANTASY_UNITY + private readonly EndPoint _ipEndPoint = new IPEndPoint(IPAddress.Any, 0); +#endif + private event Action OnConnectFail; + private event Action OnConnectComplete; + private event Action OnConnectDisconnect; + public uint ChannelId { get; private set; } + private uint TimeNow => (uint) (TimeHelper.Now - _startTime); + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.KCP, networkTarget); + _packetParser = PacketParserFactory.CreateClientBufferPacket(this); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + + if (!_isDisconnect) + { + SendDisconnect(); + } + + base.Dispose(); + ClearConnectTimeout(); + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + OnConnectDisconnect?.Invoke(); + _kcp.Dispose(); + + if (_socket.Connected) + { + _socket.Close(); + } + + _packetParser.Dispose(); + ChannelId = 0; + _isConnected = false; + _messageCache.Clear(); + } + + #region Connect + + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + if (IsInit) + { + throw new NotSupportedException($"KCPClientNetwork Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _startTime = TimeHelper.Now; + ChannelId = CreateChannelId(); + _remoteAddress = NetworkHelper.GetIPEndPoint(remoteAddress); + OnConnectFail = onConnectFail; + OnConnectComplete = onConnectComplete; + OnConnectDisconnect = onConnectDisconnect; + _connectEventArgs.Completed += OnConnectSocketCompleted; + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + OnConnectFail?.Invoke(); + Dispose(); + }); + _connectEventArgs.RemoteEndPoint = _remoteAddress; + _socket = new Socket(_remoteAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + _socket.Blocking = false; + _socket.SetSocketBufferToOsLimit(); + _socket.SetSioUdpConnReset(); + _socket.Bind(new IPEndPoint(IPAddress.Any, 0)); + _kcp = KCPFactory.Create(NetworkTarget, ChannelId, KcpSpanCallback, out var kcpSettings); + _maxSndWnd = kcpSettings.MaxSendWindowSize; + + if (!_socket.ConnectAsync(_connectEventArgs)) + { + try + { + OnReceiveSocketComplete(); + } + catch (Exception e) + { + Log.Error(e); + OnConnectFail?.Invoke(); + } + } + + Session = Session.Create(this, _remoteAddress); + return Session; + } + + private void OnConnectSocketCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + if (asyncEventArgs.LastOperation == SocketAsyncOperation.Connect) + { + if (asyncEventArgs.SocketError == SocketError.Success) + { + Scene.ThreadSynchronizationContext.Post(OnReceiveSocketComplete); + } + else + { + Scene.ThreadSynchronizationContext.Post(() => + { + OnConnectFail?.Invoke(); + Dispose(); + }); + } + } + } + + private void OnReceiveSocketComplete() + { + SendRequestConnection(); + ReadPipeDataAsync().Forget(); + ReceiveSocketAsync().Forget(); + } + + #endregion + + #region ReceiveSocket + + private async UniTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); +#if FANTASY_UNITY + MemoryMarshal.TryGetArray(memory, out ArraySegment arraySegment); + var result = await _socket.ReceiveFromAsync(arraySegment, SocketFlags.None, _ipEndPoint); + _pipe.Writer.Advance(result.ReceivedBytes); + await _pipe.Writer.FlushAsync(); +#else + var result = await _socket.ReceiveAsync(memory, SocketFlags.None, _cancellationTokenSource.Token); + _pipe.Writer.Advance(result); + await _pipe.Writer.FlushAsync(); +#endif + } + catch (SocketException) + { + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async UniTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var header, out var channelId, out var message)) + { + ReceiveData(ref header, ref channelId, ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + } + + private unsafe bool TryReadMessage(ref ReadOnlySequence buffer, out KcpHeader header, out uint channelId, out ReadOnlyMemory message) + { + if (buffer.Length < 5) + { + channelId = 0; + message = default; + header = KcpHeader.None; + if (buffer.Length > 0) + { + buffer = buffer.Slice(buffer.Length); + } + return false; + } + + var readOnlyMemory = buffer.First; + + if (MemoryMarshal.TryGetArray(readOnlyMemory, out var arraySegment)) + { + fixed (byte* bytePointer = &arraySegment.Array[arraySegment.Offset]) + { + header = (KcpHeader)bytePointer[0]; + channelId = Unsafe.ReadUnaligned(ref bytePointer[1]); + } + } + else + { + // 如果无法获取数组段,回退到安全代码来执行。这种情况几乎不会发生、为了保险还是写一下了。 + var firstSpan = readOnlyMemory.Span; + header = (KcpHeader)firstSpan[0]; + channelId = MemoryMarshal.Read(firstSpan.Slice(1, 4)); + + } + + message = readOnlyMemory.Slice(5); + buffer = buffer.Slice(readOnlyMemory.Length); + return true; + } + + private void ReceiveData(ref KcpHeader header, ref uint channelId, ref ReadOnlyMemory buffer) + { + switch (header) + { + // 发送握手给服务器 + case KcpHeader.RepeatChannelId: + { + // 到这里是客户端的channelId再服务器上已经存在、需要重新生成一个再次尝试连接 + ChannelId = CreateChannelId(); + SendRequestConnection(); + break; + } + // 收到服务器发送会来的确认握手 + case KcpHeader.WaitConfirmConnection: + { + if (channelId != ChannelId) + { + break; + } + + ClearConnectTimeout(); + SendConfirmConnection(); + OnConnectComplete?.Invoke(); + _isConnected = true; + while (_messageCache.TryDequeue(out var memoryStream)) + { + SendMemoryStream(memoryStream); + } + break; + } + // 收到服务器发送的消息 + case KcpHeader.ReceiveData: + { + if (buffer.Length == 5) + { + Log.Warning($"KCP Server KcpHeader.Data buffer.Length == 5"); + break; + } + + if (channelId != ChannelId) + { + break; + } + + Input(buffer); + break; + } + // 接收到服务器的断开连接消息 + case KcpHeader.Disconnect: + { + if (channelId != ChannelId) + { + break; + } + + _isDisconnect = true; + Dispose(); + break; + } + } + } + + private void Input(ReadOnlyMemory buffer) + { + _kcp.Input(buffer); + AddToUpdate(0); + + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var peekSize = _kcp.PeekSize(); + + if (peekSize < 0) + { + return; + } + + var receiveCount = _kcp.Receive(_receiveBuffer, peekSize); + + if (receiveCount != peekSize) + { + return; + } + + if (!_packetParser.UnPack(_receiveBuffer, ref receiveCount, out var packInfo)) + { + continue; + } + + Session.Receive(packInfo); + } + catch (ScanException e) + { + Log.Debug($"RemoteAddress:{_remoteAddress} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + #endregion + + #region Update + + public void CheckUpdate() + { + var nowTime = TimeNow; + _allowWraparound = nowTime < _updateMinTime; + + if (IsTimeGreaterThan(nowTime, _updateMinTime) && _updateTimer.Count > 0) + { + foreach (var timeId in _updateTimer) + { + if (IsTimeGreaterThan(timeId, nowTime)) + { + _updateMinTime = timeId; + break; + } + + _updateTimeOutTime.Add(timeId); + } + + foreach (var timeId in _updateTimeOutTime) + { + _updateTimer.Remove(timeId); + KcpUpdate(); + } + + _updateTimeOutTime.Clear(); + } + + _allowWraparound = true; + } + + private void AddToUpdate(uint tillTime) + { + if (tillTime == 0) + { + KcpUpdate(); + return; + } + + if (IsTimeGreaterThan(_updateMinTime, tillTime) || _updateMinTime == 0) + { + _updateMinTime = tillTime; + } + + _updateTimer.Add(tillTime); + } + + private void KcpUpdate() + { + var nowTime = TimeNow; + + try + { + _kcp.Update(nowTime); + } + catch (Exception e) + { + Log.Error(e); + } + + AddToUpdate(_kcp.Check(nowTime)); + } + + private const uint HalfMaxUint = uint.MaxValue / 2; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool IsTimeGreaterThan(uint timeId, uint nowTime) + { + if (!_allowWraparound) + { + return timeId > nowTime; + } + var diff = timeId - nowTime; + // 如果 diff 的值在 [0, HalfMaxUint] 范围内,说明 timeId 是在 nowTime 之后或相等。 + // 如果 diff 的值在 (HalfMaxUint, uint.MaxValue] 范围内,说明 timeId 是在 nowTime 之前(时间回绕的情况)。 + return diff < HalfMaxUint || diff == HalfMaxUint; + } + + #endregion + + #region Send + + private const byte KcpHeaderDisconnect = (byte)KcpHeader.Disconnect; + private const byte KcpHeaderReceiveData = (byte)KcpHeader.ReceiveData; + private const byte KcpHeaderRequestConnection = (byte)KcpHeader.RequestConnection; + private const byte KcpHeaderConfirmConnection = (byte)KcpHeader.ConfirmConnection; + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + var buffer = _packetParser.Pack(ref rpcId, ref routeId, memoryStream, message); + + if (!_isConnected) + { + _messageCache.Enqueue(buffer); + return; + } + + SendMemoryStream(buffer); + } + + private void SendMemoryStream(MemoryStreamBuffer memoryStream) + { + if (_kcp.WaitSendCount > _maxSndWnd) + { + // 检查等待发送的消息,如果超出两倍窗口大小,KCP作者给的建议是要断开连接 + Log.Warning($"ERR_KcpWaitSendSizeTooLarge {_kcp.WaitSendCount} > {_maxSndWnd}"); + Dispose(); + return; + } + + try + { + _kcp.Send(memoryStream.GetBuffer(), 0, (int)memoryStream.Position); + AddToUpdate(0); + } + finally + { + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + } + + private unsafe void SendRequestConnection() + { + try + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderRequestConnection; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(_sendBuff, 0, 5); + } + catch (Exception e) + { + Log.Error(e); + } + } + + private unsafe void SendConfirmConnection() + { + try + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderConfirmConnection; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(_sendBuff, 0, 5); + } + catch (Exception e) + { + Log.Error(e); + } + } + + private unsafe void SendDisconnect() + { + try + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderDisconnect; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(_sendBuff, 0, 5); + } + catch (Exception e) + { + Log.Error(e); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SendAsync(byte[] buffer, int offset, int count) + { + try + { + _socket.Send(new ArraySegment(buffer, offset, count), SocketFlags.None); + } + catch (ArgumentException ex) + { + Log.Error($"ArgumentException: {ex.Message}"); // 处理参数错误 + } + catch (SocketException) + { + //Log.Error($"SocketException: {ex.Message}"); // 处理网络错误 + Dispose(); + } + catch (ObjectDisposedException ex) + { + Log.Error($"ObjectDisposedException: {ex.Message}"); // 处理套接字已关闭的情况 + Dispose(); + } + catch (InvalidOperationException ex) + { + Log.Error($"InvalidOperationException: {ex.Message}"); // 处理无效操作 + } + catch (Exception ex) + { + Log.Error($"Exception: {ex.Message}"); // 捕获其他异常 + } + } + + private unsafe void KcpSpanCallback(byte[] buffer, ref int count) + { + if (IsDisposed) + { + return; + } + + if (count == 0) + { + throw new Exception("KcpOutput count 0"); + } + + fixed (byte* p = buffer) + { + p[0] = KcpHeaderReceiveData; + *(uint*)(p + 1) = ChannelId; + } + + SendAsync(buffer, 0, count + 5); + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene?.TimerComponent?.Net.Remove(ref _connectTimeoutId); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static unsafe uint CreateChannelId() + { + uint value; + RandomNumberGenerator.Fill(MemoryMarshal.CreateSpan(ref *(byte*)&value, 4)); + return 0xC0000000 | (value & int.MaxValue); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta new file mode 100644 index 00000000..0374b0bf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Client/KCPClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 955df13b771de413ebebbdb3ac07be7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KCPSettings.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KCPSettings.cs new file mode 100644 index 00000000..7e0d9264 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KCPSettings.cs @@ -0,0 +1,89 @@ +#if !FANTASY_WEBGL +using System; +using KCP; + +#pragma warning disable CS1591 +namespace Fantasy.Network.KCP +{ + public class KCPSettings + { + public int Mtu { get; private set; } + public int SendWindowSize { get; private set; } + public int ReceiveWindowSize { get; private set; } + public int MaxSendWindowSize { get; private set; } + + public static KCPSettings Create(NetworkTarget networkTarget) + { + var settings = new KCPSettings(); + + switch (networkTarget) + { + case NetworkTarget.Outer: + { + // 外网设置470的原因: + // 1、mtu设置过大有可能路由器过滤掉 + // 2、降低 mtu 到 470,同样数据虽然会发更多的包,但是小包在路由层优先级更高 + settings.Mtu = 470; +#if FANTASY_NET + settings.SendWindowSize = 8192; + settings.ReceiveWindowSize = 8192; + settings.MaxSendWindowSize = 8192 * 8192 * 7; +#endif +#if FANTASY_UNITY || FANTASY_CONSOLE + settings.SendWindowSize = 512; + settings.ReceiveWindowSize = 512; + settings.MaxSendWindowSize = 512 * 512 * 7; +#endif + + break; + } +#if FANTASY_NET + case NetworkTarget.Inner: + { + // 内网设置1400的原因 + // 1、一般都是同一台服务器来运行多个进程来处理 + // 2、内网每个进程跟其他进程只有一个通道进行发送、所以发送的数量会比较大 + // 3、如果不把窗口设置大点、会出现消息滞后。 + // 4、因为内网发送的可不只是外网转发数据、还有可能是其他进程的通讯 + settings.Mtu = 1200; + settings.SendWindowSize = 8192; + settings.ReceiveWindowSize = 8192; + settings.MaxSendWindowSize = 8192 * 8192 * 7; + break; + } +#endif + default: + { + throw new NotSupportedException($"KCPServerNetwork NotSupported NetworkType:{networkTarget}"); + } + } + + return settings; + } + } + + public static class KCPFactory + { + public static Kcp Create(NetworkTarget networkTarget, uint conv, KcpCallback output, out KCPSettings kcpSettings) + { + var kcp = new Kcp(conv, output); + kcpSettings = KCPSettings.Create(networkTarget); + kcp.SetNoDelay(1, 5, 2, 1); + kcp.SetWindowSize(kcpSettings.SendWindowSize, kcpSettings.ReceiveWindowSize); + kcp.SetMtu(kcpSettings.Mtu); + kcp.SetMinrto(30); + return kcp; + } + + public static Kcp Create(KCPSettings kcpSettings, uint conv, KcpCallback output) + { + var kcp = new Kcp(conv, output); + kcp.SetNoDelay(1, 5, 2, 1); + kcp.SetWindowSize(kcpSettings.SendWindowSize, kcpSettings.ReceiveWindowSize); + kcp.SetMtu(kcpSettings.Mtu); + kcp.SetMinrto(30); + return kcp; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KCPSettings.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KCPSettings.cs.meta new file mode 100644 index 00000000..2f95b5f6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KCPSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2852b1058f3ea4df8bc1325fbbfbf903 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KcpHeader.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KcpHeader.cs new file mode 100644 index 00000000..28ddace6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KcpHeader.cs @@ -0,0 +1,14 @@ +namespace Fantasy.Network.KCP +#pragma warning disable CS1591 +{ + public enum KcpHeader : byte + { + None = 0x00, + RequestConnection = 0x01, + WaitConfirmConnection = 0x02, + ConfirmConnection = 0x03, + RepeatChannelId = 0x04, + ReceiveData = 0x06, + Disconnect = 0x07 + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KcpHeader.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KcpHeader.cs.meta new file mode 100644 index 00000000..6c188684 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/KcpHeader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1cb57f8f94f654626bbb5ce227e13537 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server.meta new file mode 100644 index 00000000..25dc2772 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c53c8541b8381438cb4af82d9f5dfcfe +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetwork.cs new file mode 100644 index 00000000..54b550d0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetwork.cs @@ -0,0 +1,619 @@ +#if FANTASY_NET +using System.Buffers; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Fantasy.Async; +using Fantasy.DataStructure.Collection; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8602 // Dereference of a possibly null reference. + +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +namespace Fantasy.Network.KCP +{ + public sealed class KCPServerNetworkUpdateSystem : UpdateSystem + { + protected override void Update(KCPServerNetwork self) + { + self.Update(); + } + } + + public struct PendingConnection + { + public readonly uint ChannelId; + public readonly uint TimeOutId; + public readonly IPEndPoint RemoteEndPoint; + + public PendingConnection(uint channelId, IPEndPoint remoteEndPoint, uint time) + { + ChannelId = channelId; + RemoteEndPoint = remoteEndPoint; + TimeOutId = time + 10 * 1000; // 设置10秒超时,如果10秒内没有确认连接则删除。 + } + } + + public sealed class KCPServerNetwork : ANetwork + { + private Socket _socket; + private long _startTime; + private uint _updateMinTime; + private uint _pendingMinTime; + private bool _allowWraparound = true; + private readonly Pipe _pipe = new Pipe(); + private readonly byte[] _sendBuff = new byte[5]; + private readonly List _pendingTimeOutTime = new List(); + private readonly HashSet _updateChannels = new HashSet(); + private readonly List _updateTimeOutTime = new List(); + private readonly Queue _endPoint = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private readonly SortedOneToManyList _updateTimer = new SortedOneToManyList(); + + private readonly Dictionary _pendingConnection = new Dictionary(); + private readonly SortedOneToManyList _pendingConnectionTimeOut = new SortedOneToManyList(); + private readonly Dictionary _connectionChannel = new Dictionary(); + + public KCPSettings Settings { get; private set; } + + private uint TimeNow => (uint)(TimeHelper.Now - _startTime); + + public void Initialize(NetworkTarget networkTarget, IPEndPoint address) + { + _startTime = TimeHelper.Now; + Settings = KCPSettings.Create(networkTarget); + base.Initialize(NetworkType.Server, NetworkProtocolType.KCP, networkTarget); + _socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + _socket.Blocking = false; + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + _socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); + } + + _socket.Blocking = false; + _socket.Bind(address); + _socket.SetSocketBufferToOsLimit(); + _socket.SetSioUdpConnReset(); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} networkTarget = {networkTarget.ToString()} KCPServer Listen {address}"); + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + foreach (var (_, channel) in _connectionChannel.ToArray()) + { + channel.Dispose(); + } + + _connectionChannel.Clear(); + _pendingConnection.Clear(); + + if (_socket != null) + { + _socket.Dispose(); + _socket = null; + } + + base.Dispose(); + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); + + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + var socketReceiveFromResult = await _socket.ReceiveFromAsync(memory, SocketFlags.None, remoteEndPoint, _cancellationTokenSource.Token); + var receivedBytes = socketReceiveFromResult.ReceivedBytes; + + if (receivedBytes == 5) + { + switch ((KcpHeader)memory.Span[0]) + { + case KcpHeader.RequestConnection: + case KcpHeader.ConfirmConnection: + { + _endPoint.Enqueue(socketReceiveFromResult.RemoteEndPoint.Clone()); + break; + } + } + } + + _pipe.Writer.Advance(receivedBytes); + await _pipe.Writer.FlushAsync(); + } + catch (SocketException ex) + { + Log.Error($"Socket exception: {ex.Message}"); + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var header, out var channelId, out var message)) + { + ReceiveData(ref header, ref channelId, ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private unsafe bool TryReadMessage(ref ReadOnlySequence buffer, out KcpHeader header, out uint channelId, out ReadOnlyMemory message) + { + if (buffer.Length < 5) + { + channelId = 0; + message = default; + header = KcpHeader.None; + if (buffer.Length > 0) + { + buffer = buffer.Slice(buffer.Length); + } + return false; + } + + var readOnlyMemory = buffer.First; + + if (MemoryMarshal.TryGetArray(readOnlyMemory, out var arraySegment)) + { + fixed (byte* bytePointer = &arraySegment.Array[arraySegment.Offset]) + { + header = (KcpHeader)bytePointer[0]; + channelId = Unsafe.ReadUnaligned(ref bytePointer[1]); + } + } + else + { + // 如果无法获取数组段,回退到安全代码来执行。这种情况几乎不会发生、为了保险还是写一下了。 + var firstSpan = readOnlyMemory.Span; + header = (KcpHeader)firstSpan[0]; + channelId = MemoryMarshal.Read(firstSpan.Slice(1, 4)); + } + + message = readOnlyMemory.Slice(5); + buffer = buffer.Slice(readOnlyMemory.Length); + return true; + } + + private void ReceiveData(ref KcpHeader header, ref uint channelId, ref ReadOnlyMemory buffer) + { + switch (header) + { + // 客户端请求建立KCP连接 + case KcpHeader.RequestConnection: + { + _endPoint.TryDequeue(out var ipEndPoint); + + if (_pendingConnection.TryGetValue(channelId, out var pendingConnection)) + { + if (!ipEndPoint.IPEndPointEquals(pendingConnection.RemoteEndPoint)) + { + // 重复通道ID,向客户端发送重复通道ID消息 + SendRepeatChannelId(ref channelId, ipEndPoint); + } + + break; + } + + if (_connectionChannel.ContainsKey(channelId)) + { + // 已存在的通道ID,向客户端发送重复通道ID消息 + SendRepeatChannelId(ref channelId, ipEndPoint); + break; + } + + AddPendingConnection(ref channelId, ipEndPoint); + break; + } + // 客户端确认建立KCP连接 + case KcpHeader.ConfirmConnection: + { + _endPoint.TryDequeue(out var ipEndPoint); + if (!ConfirmPendingConnection(ref channelId, ipEndPoint)) + { + break; + } + + AddConnection(ref channelId, ipEndPoint.Clone()); + break; + } + // 接收KCP的数据 + case KcpHeader.ReceiveData: + { + if (buffer.Length == 5) + { + Log.Warning($"KCP Server KcpHeader.Data buffer.Length == 5"); + break; + } + + if (_connectionChannel.TryGetValue(channelId, out var channel)) + { + channel.Input(buffer); + } + + break; + } + // 断开KCP连接 + case KcpHeader.Disconnect: + { + // 断开不需要清楚PendingConnection让ClearPendingConnection自动清楚就可以了,并且不一定有Pending。 + RemoveChannel(channelId); + break; + } + } + } + + #endregion + + #region Update + + public void Update() + { + var timeNow = TimeNow; + _allowWraparound = timeNow < _updateMinTime; + CheckUpdateTimerOut(ref timeNow); + UpdateChannel(ref timeNow); + PendingTimerOut(ref timeNow); + _allowWraparound = true; + } + + private void CheckUpdateTimerOut(ref uint nowTime) + { + if (_updateTimer.Count == 0) + { + return; + } + + if (IsTimeGreaterThan(_updateMinTime, nowTime)) + { + return; + } + + _updateTimeOutTime.Clear(); + + foreach (var kv in _updateTimer) + { + var timeId = kv.Key; + + if (IsTimeGreaterThan(timeId, nowTime)) + { + _updateMinTime = timeId; + break; + } + + _updateTimeOutTime.Add(timeId); + } + + foreach (var timeId in _updateTimeOutTime) + { + foreach (var channelId in _updateTimer[timeId]) + { + _updateChannels.Add(channelId); + } + + _updateTimer.RemoveKey(timeId); + } + } + + private void UpdateChannel(ref uint timeNow) + { + foreach (var channelId in _updateChannels) + { + if (!_connectionChannel.TryGetValue(channelId, out var channel)) + { + continue; + } + + if (channel.IsDisposed) + { + _connectionChannel.Remove(channelId); + continue; + } + + channel.Kcp.Update(timeNow); + AddUpdateChannel(channelId, channel.Kcp.Check(timeNow)); + } + + _updateChannels.Clear(); + } + + private void PendingTimerOut(ref uint timeNow) + { + if (_pendingConnectionTimeOut.Count == 0) + { + return; + } + + if (IsTimeGreaterThan(_pendingMinTime, timeNow)) + { + return; + } + + _pendingTimeOutTime.Clear(); + + foreach (var kv in _pendingConnectionTimeOut) + { + var timeId = kv.Key; + + if (IsTimeGreaterThan(timeId, timeNow)) + { + _pendingMinTime = timeId; + break; + } + + _pendingTimeOutTime.Add(timeId); + } + + foreach (var timeId in _pendingTimeOutTime) + { + foreach (var channelId in _pendingConnectionTimeOut[timeId]) + { + _pendingConnection.Remove(channelId); + } + + _pendingConnectionTimeOut.RemoveKey(timeId); + } + } + + public void AddUpdateChannel(uint channelId, uint tillTime) + { + if (tillTime == 0) + { + _updateChannels.Add(channelId); + return; + } + + if (IsTimeGreaterThan(_updateMinTime, tillTime)) + { + _updateMinTime = tillTime; + } + + _updateTimer.Add(tillTime, channelId); + } + + private const uint HalfMaxUint = uint.MaxValue / 2; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool IsTimeGreaterThan(uint timeId, uint nowTime) + { + if (!_allowWraparound) + { + return timeId > nowTime; + } + + var diff = timeId - nowTime; + // 如果 diff 的值在 [0, HalfMaxUint] 范围内,说明 timeId 是在 nowTime 之后或相等。 + // 如果 diff 的值在 (HalfMaxUint, uint.MaxValue] 范围内,说明 timeId 是在 nowTime 之前(时间回绕的情况)。 + return diff < HalfMaxUint || diff == HalfMaxUint; + } + + #endregion + + #region Pending + + private void AddPendingConnection(ref uint channelId, IPEndPoint ipEndPoint) + { + var now = TimeNow; + var pendingConnection = new PendingConnection(channelId, ipEndPoint, now); + + if (IsTimeGreaterThan(_pendingMinTime, pendingConnection.TimeOutId) || _pendingMinTime == 0) + { + _pendingMinTime = pendingConnection.TimeOutId; + } + + _pendingConnection.Add(channelId, pendingConnection); + _pendingConnectionTimeOut.Add(pendingConnection.TimeOutId, channelId); + SendWaitConfirmConnection(ref channelId, ipEndPoint); + } + + private bool ConfirmPendingConnection(ref uint channelId, EndPoint ipEndPoint) + { + if (!_pendingConnection.TryGetValue(channelId, out var pendingConnection)) + { + return false; + } + + if (!ipEndPoint.IPEndPointEquals(pendingConnection.RemoteEndPoint)) + { + Log.Error($"KCPSocket syn address diff: {channelId} {pendingConnection.RemoteEndPoint} {ipEndPoint}"); + return false; + } + + _pendingConnection.Remove(channelId); + _pendingConnectionTimeOut.RemoveValue(pendingConnection.TimeOutId, pendingConnection.ChannelId); +#if FANTASY_DEVELOP + Log.Debug($"KCPSocket _pendingConnection:{_pendingConnection.Count} _pendingConnectionTimer:{_pendingConnectionTimeOut.Count}"); +#endif + return true; + } + + #endregion + + #region Connection + + private void AddConnection(ref uint channelId, IPEndPoint ipEndPoint) + { + var eventArgs = new KCPServerNetworkChannel(this, channelId, ipEndPoint); + _connectionChannel.Add(channelId, eventArgs); +#if FANTASY_DEVELOP + Log.Debug($"AddConnection _connectionChannel:{_connectionChannel.Count()}"); +#endif + } + + public override void RemoveChannel(uint channelId) + { + if (!_connectionChannel.Remove(channelId, out var channel)) + { + return; + } + + if (!channel.IsDisposed) + { + SendDisconnect(ref channelId, channel.RemoteEndPoint); + channel.Dispose(); + } +#if FANTASY_DEVELOP + Log.Debug($"RemoveChannel _connectionChannel:{_connectionChannel.Count()}"); +#endif + } + + #endregion + + #region Send + + private const byte KcpHeaderDisconnect = (byte)KcpHeader.Disconnect; + private const byte KcpHeaderRepeatChannelId = (byte)KcpHeader.RepeatChannelId; + private const byte KcpHeaderWaitConfirmConnection = (byte)KcpHeader.WaitConfirmConnection; + + private unsafe void SendDisconnect(ref uint channelId, EndPoint clientEndPoint) + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderDisconnect; + *(uint*)(p + 1) = channelId; + } + + SendAsync(_sendBuff, 0, 5, clientEndPoint); + } + + private unsafe void SendRepeatChannelId(ref uint channelId, EndPoint clientEndPoint) + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderRepeatChannelId; + *(uint*)(p + 1) = channelId; + } + + SendAsync(_sendBuff, 0, 5, clientEndPoint); + } + + private unsafe void SendWaitConfirmConnection(ref uint channelId, EndPoint clientEndPoint) + { + fixed (byte* p = _sendBuff) + { + p[0] = KcpHeaderWaitConfirmConnection; + *(uint*)(p + 1) = channelId; + } + + SendAsync(_sendBuff, 0, 5, clientEndPoint); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SendAsync(byte[] buffer, int offset, int count, EndPoint endPoint) + { + try + { + _socket.SendTo(new ArraySegment(buffer, offset, count), SocketFlags.None, endPoint); + } + catch (ArgumentException ex) + { + Log.Error($"ArgumentException: {ex.Message}"); // 处理参数错误 + } + catch (SocketException) + { + //Log.Error($"SocketException: {ex.Message}"); // 处理网络错误 + } + catch (ObjectDisposedException) + { + // 处理套接字已关闭的情况 + } + catch (InvalidOperationException ex) + { + Log.Error($"InvalidOperationException: {ex.Message}"); // 处理无效操作 + } + catch (Exception ex) + { + Log.Error($"Exception: {ex.Message}"); // 捕获其他异常 + } + } + + #endregion + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetwork.cs.meta new file mode 100644 index 00000000..591d1e8d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a343a9ffd343542aa96d21c234cb0605 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs new file mode 100644 index 00000000..3d5be09a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs @@ -0,0 +1,155 @@ +#if FANTASY_NET +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +using KCP; +// ReSharper disable ParameterHidesMember +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.KCP +{ + /// + /// KCP 服务器网络通道,用于处理服务器与客户端之间的数据通信。 + /// + public class KCPServerNetworkChannel : ANetworkServerChannel + { + private bool _isInnerDispose; + private readonly int _maxSndWnd; + private KCPServerNetwork _kcpServerNetwork; + private readonly BufferPacketParser _packetParser; + private readonly byte[] _receiveBuffer = new byte[Packet.PacketBodyMaxLength + 20]; + public Kcp Kcp { get; private set; } + public uint ChannelId { get; private set; } + + public KCPServerNetworkChannel(KCPServerNetwork network, uint channelId, IPEndPoint ipEndPoint) : base(network, channelId, ipEndPoint) + { + _kcpServerNetwork = network; + ChannelId = channelId; + _maxSndWnd = network.Settings.MaxSendWindowSize; + Kcp = KCPFactory.Create(network.Settings, ChannelId, KcpSpanCallback); + _packetParser = PacketParserFactory.CreateServerBufferPacket(network); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + _kcpServerNetwork.RemoveChannel(Id); + base.Dispose(); + IsDisposed = true; + Kcp.Dispose(); + Kcp = null; + ChannelId = 0; + _kcpServerNetwork = null; + } + + public void Input(ReadOnlyMemory buffer) + { + Kcp.Input(buffer); + _kcpServerNetwork.AddUpdateChannel(ChannelId, 0); + + while (!IsDisposed) + { + try + { + var peekSize = Kcp.PeekSize(); + + if (peekSize < 0) + { + return; + } + + var receiveCount = Kcp.Receive(_receiveBuffer, peekSize); + + if (receiveCount != peekSize) + { + return; + } + + if (!_packetParser.UnPack(_receiveBuffer, ref receiveCount, out var packInfo)) + { + continue; + } + + Session.Receive(packInfo); + } + catch (ScanException e) + { + Log.Debug($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + if (IsDisposed) + { + return; + } + + if (Kcp.WaitSendCount > _maxSndWnd) + { + // 检查等待发送的消息,如果超出两倍窗口大小,KCP作者给的建议是要断开连接 + Log.Warning($"ERR_KcpWaitSendSizeTooLarge {Kcp.WaitSendCount} > {_maxSndWnd}"); + Dispose(); + return; + } + + var buffer = _packetParser.Pack(ref rpcId, ref routeId, memoryStream, message); + Kcp.Send(buffer.GetBuffer(), 0, (int)buffer.Position); + + if (buffer.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + _kcpServerNetwork.MemoryStreamBufferPool.ReturnMemoryStream(buffer); + } + + _kcpServerNetwork.AddUpdateChannel(ChannelId, 0); + } + + private const byte KcpHeaderReceiveData = (byte)KcpHeader.ReceiveData; + + private unsafe void KcpSpanCallback(byte[] buffer, ref int count) + { + if (IsDisposed) + { + return; + } + + try + { + if (count == 0) + { + throw new Exception("KcpOutput count 0"); + } + + fixed (byte* p = buffer) + { + p[0] = KcpHeaderReceiveData; + *(uint*)(p + 1) = ChannelId; + } + + _kcpServerNetwork.SendAsync(buffer, 0, count + 5, RemoteEndPoint); + } + catch (Exception e) + { + Log.Error(e); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta new file mode 100644 index 00000000..7f81daee --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/KCP/Server/KCPServerNetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a8056a8265742483686fb10fb351d108 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolFactory.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolFactory.cs new file mode 100644 index 00000000..79da439e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolFactory.cs @@ -0,0 +1,97 @@ +using System; +using System.Net; +using Fantasy.Entitas; +using Fantasy.Helper; +using Fantasy.Network.Interface; +#if !FANTASY_WEBGL +using Fantasy.Network.TCP; +using Fantasy.Network.KCP; +#endif +#if FANTASY_NET +using Fantasy.Network.HTTP; +#endif +using Fantasy.Network.WebSocket; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network +{ + internal static class NetworkProtocolFactory + { +#if FANTASY_NET + public static ANetwork CreateServer(Scene scene, NetworkProtocolType protocolType, NetworkTarget networkTarget, string bindIp, int port, bool isHttps = false) + { + switch (protocolType) + { + case NetworkProtocolType.TCP: + { + var network = Entity.Create(scene, false, false); + var address = NetworkHelper.ToIPEndPoint(bindIp, port); + network.Initialize(networkTarget, address); + return network; + } + case NetworkProtocolType.KCP: + { + var network = Entity.Create(scene, false, true); + var address = NetworkHelper.ToIPEndPoint(bindIp, port); + network.Initialize(networkTarget, address); + return network; + } + case NetworkProtocolType.WebSocket: + { + var network = Entity.Create(scene, false, true); + var urls = isHttps ? new [] { $"https://{bindIp}:{port}/" } : new [] { $"http://{bindIp}:{port}/" }; + network.Initialize(networkTarget, urls); + return network; + } + case NetworkProtocolType.HTTP: + { + var network = Entity.Create(scene, false, true); + var urls = isHttps ? new [] { $"https://{bindIp}:{port}/" } : new [] { $"http://{bindIp}:{port}/" }; + network.Initialize(networkTarget, urls); + return network; + } + default: + { + throw new NotSupportedException($"Unsupported NetworkProtocolType:{protocolType}"); + } + } + } +#endif + public static AClientNetwork CreateClient(Scene scene, NetworkProtocolType protocolType, NetworkTarget networkTarget) + { +#if !FANTASY_WEBGL + switch (protocolType) + { + case NetworkProtocolType.TCP: + { + var network = Entity.Create(scene, false, false); + network.Initialize(networkTarget); + return network; + } + case NetworkProtocolType.KCP: + { + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget); + return network; + } + case NetworkProtocolType.WebSocket: + { + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget); + return network; + } + default: + { + throw new NotSupportedException($"Unsupported NetworkProtocolType:{protocolType}"); + } + } +#else + // Webgl平台只能用这个协议。 + var network = Entity.Create(scene, false, true); + network.Initialize(networkTarget); + return network; +#endif + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta new file mode 100644 index 00000000..cea246ff --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e9f2a5ed9c13448c89afe62abe02493b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolType.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolType.cs new file mode 100644 index 00000000..55a04c9c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolType.cs @@ -0,0 +1,69 @@ +namespace Fantasy.Network +{ + /// + /// 网络服务器类型 + /// + public enum NetworkType + { + /// + /// 默认 + /// + None = 0, + /// + /// 客户端网络 + /// + Client = 1, +#if FANTASY_NET + /// + /// 服务器网络 + /// + Server = 2 +#endif + } + /// + /// 网络服务的目标 + /// + public enum NetworkTarget + { + /// + /// 默认 + /// + None = 0, + /// + /// 对外 + /// + Outer = 1, +#if FANTASY_NET + /// + /// 对内 + /// + Inner = 2 +#endif + } + /// + /// 支持的网络协议 + /// + public enum NetworkProtocolType + { + /// + /// 默认 + /// + None = 0, + /// + /// KCP + /// + KCP = 1, + /// + /// TCP + /// + TCP = 2, + /// + /// WebSocket + /// + WebSocket = 3, + /// + /// HTTP + /// + HTTP = 4, + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolType.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolType.cs.meta new file mode 100644 index 00000000..077f6764 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkProtocolType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ff164a3b41dd74f5cad6a738ffd77591 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkThreadComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkThreadComponent.cs new file mode 100644 index 00000000..c0c166bf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkThreadComponent.cs @@ -0,0 +1,100 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Threading; +using Fantasy.Entitas; +// ReSharper disable ForCanBeConvertedToForeach +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Network +{ + internal interface INetworkThreadUpdate + { + void Update(); + } + + /// + /// 网络线程组件 + /// + internal sealed class NetworkThreadComponent : Entity + { + private Thread _netWorkThread; + internal ThreadSynchronizationContext SynchronizationContext { get; private set; } + private readonly List _updates = new List(); + + internal NetworkThreadComponent Initialize() + { + SynchronizationContext = new ThreadSynchronizationContext(); + _netWorkThread = new Thread(Update) + { + IsBackground = true + }; + _netWorkThread.Start(); + return this; + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + SynchronizationContext.Post(() => + { + _updates.Clear(); + _netWorkThread.Join(); + _netWorkThread = null; + SynchronizationContext = null; + }); + + base.Dispose(); + } + + private void Update() + { + // 将同步上下文设置为网络线程的上下文,以确保操作在正确的线程上下文中执行。 + System.Threading.SynchronizationContext.SetSynchronizationContext(SynchronizationContext); + // 循环执行 + while (!IsDisposed) + { + for (var i = 0; i < _updates.Count; i++) + { + try + { + _updates[i].Update(); + } + catch (Exception e) + { + Log.Error(e); + } + } + SynchronizationContext.Update(); + Thread.Sleep(1); + } + } + + internal void AddNetworkThreadUpdate(INetworkThreadUpdate update) + { + SynchronizationContext.Post(() => + { + if (_updates.Contains(update)) + { + Log.Warning($"{update.GetType().FullName} Network thread update is already running"); + return; + } + _updates.Add(update); + }); + } + + internal void RemoveNetworkThreadUpdate(INetworkThreadUpdate update) + { + SynchronizationContext.Post(() => + { + _updates.Remove(update); + }); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkThreadComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkThreadComponent.cs.meta new file mode 100644 index 00000000..5b8daddb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/NetworkThreadComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd76246170d9546a2a504a922cda29ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP.meta new file mode 100644 index 00000000..a540377f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 015b2c41a11614c19847def0749c75d3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client.meta new file mode 100644 index 00000000..9b978227 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 637e4cf1e0eb049efb57f91f75d645e7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs new file mode 100644 index 00000000..69c216b1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs @@ -0,0 +1,404 @@ +#if !FANTASY_WEBGL +using System; +using System.Buffers; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Threading; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +namespace Fantasy.Network.TCP +{ + public sealed class TCPClientNetwork : AClientNetwork + { + private bool _isSending; + private bool _isInnerDispose; + private long _connectTimeoutId; + private Socket _socket; + private IPEndPoint _remoteEndPoint; + private SocketAsyncEventArgs _sendArgs; + private ReadOnlyMemoryPacketParser _packetParser; + private readonly Pipe _pipe = new Pipe(); + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + private Action _onConnectFail; + private Action _onConnectComplete; + private Action _onConnectDisconnect; + + public uint ChannelId { get; private set; } + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.TCP, networkTarget); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + base.Dispose(); + _isSending = false; + _isInnerDispose = true; + ClearConnectTimeout(); + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + _onConnectDisconnect?.Invoke(); + + if (_socket.Connected) + { + _socket.Close(); + _socket = null; + } + + _sendBuffers.Clear(); + _packetParser?.Dispose(); + ChannelId = 0; + _sendArgs = null; + } + + /// + /// 连接到远程服务器。 + /// + /// 远程服务器的终端点。 + /// 连接成功时的回调。 + /// 连接失败时的回调。 + /// 连接断开时的回调。 + /// + /// 连接超时时间,单位:毫秒。 + /// 连接的会话。 + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + // 如果已经初始化过一次,抛出异常,要求重新实例化 + + if (IsInit) + { + throw new NotSupportedException("TCPClientNetwork Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _isSending = false; + _onConnectFail = onConnectFail; + _onConnectComplete = onConnectComplete; + _onConnectDisconnect = onConnectDisconnect; + // 设置连接超时定时器 + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + _packetParser = PacketParserFactory.CreateClientReadOnlyMemoryPacket(this); + _remoteEndPoint = NetworkHelper.GetIPEndPoint(remoteAddress); + _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _socket.NoDelay = true; + _socket.SetSocketBufferToOsLimit(); + _sendArgs = new SocketAsyncEventArgs(); + _sendArgs.Completed += OnSendCompleted; + var outArgs = new SocketAsyncEventArgs + { + RemoteEndPoint = _remoteEndPoint + }; + outArgs.Completed += OnConnectSocketCompleted; + + if (!_socket.ConnectAsync(outArgs)) + { + OnReceiveSocketComplete(); + } + + Session = Session.Create(this, _remoteEndPoint); + return Session; + } + + private void OnConnectSocketCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + if (asyncEventArgs.LastOperation == SocketAsyncOperation.Connect) + { + if (asyncEventArgs.SocketError == SocketError.Success) + { + Scene.ThreadSynchronizationContext.Post(OnReceiveSocketComplete); + } + else + { + Scene.ThreadSynchronizationContext.Post(() => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + } + } + } + + private void OnReceiveSocketComplete() + { + ClearConnectTimeout(); + _onConnectComplete?.Invoke(); + ReadPipeDataAsync().Forget(); + ReceiveSocketAsync().Forget(); + } + + #region ReceiveSocket + + private async UniTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); +#if UNITY_2021 + // Unity2021.3.14f有个恶心的问题,使用ReceiveAsync会导致memory不能正确写入 + // 所有只能使用ReceiveFromAsync来接收消息,但ReceiveFromAsync只有一个接受ArraySegment的接口。 + MemoryMarshal.TryGetArray(memory, out ArraySegment arraySegment); + var result = await _socket.ReceiveFromAsync(arraySegment, SocketFlags.None, _remoteEndPoint); + _pipe.Writer.Advance(result.ReceivedBytes); +#else + var count = await _socket.ReceiveAsync(memory, SocketFlags.None, _cancellationTokenSource.Token); + _pipe.Writer.Advance(count); +#endif + await _pipe.Writer.FlushAsync(); + } + catch (SocketException) + { + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async UniTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning(e.Message); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send(); + } + } + + private void Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_sendBuffers.Count > 0) + { + var memoryStreamBuffer = _sendBuffers.Dequeue(); + _sendArgs.UserToken = memoryStreamBuffer; + _sendArgs.SetBuffer(new ArraySegment(memoryStreamBuffer.GetBuffer(), 0, (int)memoryStreamBuffer.Position)); + + try + { + if (_socket.SendAsync(_sendArgs)) + { + break; + } + + ReturnMemoryStream(memoryStreamBuffer); + } + catch + { + _isSending = false; + return; + } + } + + _isSending = false; + } + + private void ReturnMemoryStream(MemoryStreamBuffer memoryStream) + { + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + + private void OnSendCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (asyncEventArgs.SocketError != SocketError.Success || asyncEventArgs.BytesTransferred == 0) + { + _isSending = false; + return; + } + + var memoryStreamBuffer = (MemoryStreamBuffer)asyncEventArgs.UserToken; + Scene.ThreadSynchronizationContext.Post(() => + { + ReturnMemoryStream(memoryStreamBuffer); + + if (_sendBuffers.Count > 0) + { + Send(); + } + else + { + _isSending = false; + } + }); + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene.TimerComponent.Net.Remove(ref _connectTimeoutId); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta new file mode 100644 index 00000000..e8ac2c05 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Client/TCPClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b29ef40368e94d9c90e051b8361a7f4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server.meta new file mode 100644 index 00000000..41039fb5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b700d7ce7028041c1a83dd03f7402b10 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs new file mode 100644 index 00000000..3f3d5316 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs @@ -0,0 +1,151 @@ +#if FANTASY_NET +using System.Net; +using System.Net.Sockets; +using Fantasy.Helper; +using Fantasy.Network.Interface; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +// ReSharper disable GCSuppressFinalizeForTypeWithoutDestructor +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Network.TCP +{ + public sealed class TCPServerNetwork : ANetwork + { + private Random _random; + private Socket _socket; + private SocketAsyncEventArgs _acceptAsync; + private readonly Dictionary _connectionChannel = new Dictionary(); + + public void Initialize(NetworkTarget networkTarget, IPEndPoint address) + { + base.Initialize(NetworkType.Server, NetworkProtocolType.TCP, networkTarget); + _random = new Random(); + _acceptAsync = new SocketAsyncEventArgs(); + _socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); + + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + _socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); + } + + _socket.Bind(address); + _socket.Listen(int.MaxValue); + _socket.SetSocketBufferToOsLimit(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} networkTarget = {networkTarget.ToString()} TCPServer Listen {address}"); + _acceptAsync.Completed += OnCompleted; + AcceptAsync(); + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + foreach (var networkChannel in _connectionChannel.Values.ToArray()) + { + networkChannel.Dispose(); + } + + _connectionChannel.Clear(); + _random = null; + _socket.Dispose(); + _socket = null; + _acceptAsync.Dispose(); + _acceptAsync = null; + GC.SuppressFinalize(this); + base.Dispose(); + } + + private void AcceptAsync() + { + _acceptAsync.AcceptSocket = null; + + if (_socket.AcceptAsync(_acceptAsync)) + { + return; + } + + OnAcceptComplete(_acceptAsync); + } + + private void OnAcceptComplete(SocketAsyncEventArgs asyncEventArgs) + { + if (asyncEventArgs.AcceptSocket == null) + { + return; + } + + if (asyncEventArgs.SocketError != SocketError.Success) + { + Log.Error($"Socket Accept Error: {_acceptAsync.SocketError}"); + return; + } + + try + { + uint channelId; + do + { + channelId = 0xC0000000 | (uint)_random.Next(); + } while (_connectionChannel.ContainsKey(channelId)); + + _connectionChannel.Add(channelId, new TCPServerNetworkChannel(this, asyncEventArgs.AcceptSocket, channelId)); + } + catch (Exception e) + { + Log.Error(e); + } + finally + { + AcceptAsync(); + } + } + + public override void RemoveChannel(uint channelId) + { + if (IsDisposed || !_connectionChannel.Remove(channelId, out var channel)) + { + return; + } + + if (channel.IsDisposed) + { + return; + } + + channel.Dispose(); + } + + #region 网络线程(由Socket底层产生的线程) + + private void OnCompleted(object sender, SocketAsyncEventArgs asyncEventArgs) + { + switch (asyncEventArgs.LastOperation) + { + case SocketAsyncOperation.Accept: + { + Scene.ThreadSynchronizationContext.Post(() => + { + OnAcceptComplete(asyncEventArgs); + }); + break; + } + default: + { + throw new Exception($"Socket Accept Error: {asyncEventArgs.LastOperation}"); + } + } + } + + #endregion + } +} +#endif + + diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta new file mode 100644 index 00000000..14db6222 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e618ab398f9d443a4b5b85ec4ed611c3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs new file mode 100644 index 00000000..122a54f0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs @@ -0,0 +1,295 @@ +#if FANTASY_NET +using System.Buffers; +using System.IO.Pipelines; +using System.Net.Sockets; +using Fantasy.Async; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. + +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8622 // Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes). + +namespace Fantasy.Network.TCP +{ + public sealed class TCPServerNetworkChannel : ANetworkServerChannel + { + private bool _isSending; + private bool _isInnerDispose; + private readonly Socket _socket; + private readonly ANetwork _network; + private readonly Pipe _pipe = new Pipe(); + private readonly SocketAsyncEventArgs _sendArgs; + private readonly ReadOnlyMemoryPacketParser _packetParser; + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + public TCPServerNetworkChannel(ANetwork network, Socket socket, uint id) : base(network, id, socket.RemoteEndPoint) + { + _socket = socket; + _network = network; + _socket.NoDelay = true; + _sendArgs = new SocketAsyncEventArgs(); + _sendArgs.Completed += OnSendCompletedHandler; + _packetParser = PacketParserFactory.CreateServerReadOnlyMemoryPacket(network); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + _network.RemoveChannel(Id); + + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + base.Dispose(); + + if (_socket != null) + { + _socket.Shutdown(SocketShutdown.Both); + _socket.Close(); + } + + _sendBuffers.Clear(); + _packetParser.Dispose(); + _isSending = false; + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + var count = await _socket.ReceiveAsync(memory, SocketFlags.None, _cancellationTokenSource.Token); + + if (count == 0) + { + Dispose(); + return; + } + + _pipe.Writer.Advance(count); + await _pipe.Writer.FlushAsync(); + } + catch (SocketException) + { + Dispose(); + break; + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (Exception ex) + { + Log.Error($"Unexpected exception: {ex.Message}"); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send(); + } + } + + private void Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_sendBuffers.Count > 0) + { + var memoryStreamBuffer = _sendBuffers.Dequeue(); + _sendArgs.UserToken = memoryStreamBuffer; + _sendArgs.SetBuffer(new ArraySegment(memoryStreamBuffer.GetBuffer(), 0, (int)memoryStreamBuffer.Position)); + + try + { + if (_socket.SendAsync(_sendArgs)) + { + break; + } + + ReturnMemoryStream(memoryStreamBuffer); + } + catch + { + _isSending = false; + return; + } + } + + _isSending = false; + } + + private void ReturnMemoryStream(MemoryStreamBuffer memoryStream) + { + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + _network.MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + + private void OnSendCompletedHandler(object sender, SocketAsyncEventArgs asyncEventArgs) + { + if (asyncEventArgs.SocketError != SocketError.Success || asyncEventArgs.BytesTransferred == 0) + { + _isSending = false; + return; + } + + var memoryStreamBuffer = (MemoryStreamBuffer)asyncEventArgs.UserToken; + + Scene.ThreadSynchronizationContext.Post(() => + { + ReturnMemoryStream(memoryStreamBuffer); + + if (_sendBuffers.Count > 0) + { + Send(); + } + else + { + _isSending = false; + } + }); + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta new file mode 100644 index 00000000..ef3711c2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/TCP/Server/TCPServerNetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2a73037f999c4c049abbfe87bc204e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket.meta new file mode 100644 index 00000000..78eb6b72 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 048697d76e7714069b65df11a8fe9301 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client.meta new file mode 100644 index 00000000..3fafd072 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0334c898391de44599ca09be9f560dd3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs new file mode 100644 index 00000000..46c9d22f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs @@ -0,0 +1,331 @@ +#if FANTASY_NET || FANTASY_CONSOLE +using System.Buffers; +using System.IO.Pipelines; +using System.Net.WebSockets; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +namespace Fantasy.Network.WebSocket +{ + public sealed class WebSocketClientNetwork : AClientNetwork + { + private bool _isSending; + private bool _isInnerDispose; + private long _connectTimeoutId; + private ClientWebSocket _clientWebSocket; + private ReadOnlyMemoryPacketParser _packetParser; + private readonly Pipe _pipe = new Pipe(); + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + private Action _onConnectFail; + private Action _onConnectComplete; + private Action _onConnectDisconnect; + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.WebSocket, networkTarget); + _packetParser = PacketParserFactory.CreateClientReadOnlyMemoryPacket(this); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + + base.Dispose(); + ClearConnectTimeout(); + WebSocketClientDisposeAsync().Coroutine(); + _onConnectDisconnect?.Invoke(); + _packetParser.Dispose(); + _packetParser = null; + _isSending = false; + } + + private async FTask WebSocketClientDisposeAsync() + { + if (_clientWebSocket == null) + { + return; + } + + await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None); + _clientWebSocket.Dispose(); + _clientWebSocket = null; + } + + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + if (IsInit) + { + throw new NotSupportedException( + $"WebSocketClientNetwork Id:{Id} Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _onConnectFail = onConnectFail; + _onConnectComplete = onConnectComplete; + _onConnectDisconnect = onConnectDisconnect; + // 设置连接超时定时器 + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + + _clientWebSocket = new ClientWebSocket(); + var webSocketAddress = WebSocketHelper.GetWebSocketAddress(remoteAddress, isHttps); + + try + { + _clientWebSocket.ConnectAsync(new Uri(webSocketAddress), _cancellationTokenSource.Token).Wait(); + + if (_cancellationTokenSource.IsCancellationRequested) + { + return null; + } + } + catch (WebSocketException wse) + { + Log.Error($"WebSocket error: {wse.Message}"); + Dispose(); + return null; + } + catch (Exception e) + { + Log.Error($"An error occurred: {e.Message}"); + Dispose(); + return null; + } + + ClearConnectTimeout(); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + _onConnectComplete?.Invoke(); + Session = Session.Create(this, null); + return Session; + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + // 这里接收的数据不一定是一个完整的包。如果大于8192就会分成多个包。 + var receiveResult = await _clientWebSocket.ReceiveAsync(memory, _cancellationTokenSource.Token); + + if (receiveResult.MessageType == WebSocketMessageType.Close) + { + break; + } + + var count = receiveResult.Count; + + if (count > 0) + { + await PipeWriterFlushAsync(count); + } + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (WebSocketException wse) + { + Log.Error($"WebSocket error: {wse.Message}"); + Dispose(); + break; + } + catch (Exception e) + { + Log.Error(e); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + private async FTask PipeWriterFlushAsync(int count) + { + _pipe.Writer.Advance(count); + await _pipe.Writer.FlushAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning(e.Message); + Dispose(); + } + catch (Exception e) + { + Log.Error(e); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send().Coroutine(); + } + } + + private async FTask Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_isSending) + { + if (!_sendBuffers.TryDequeue(out var memoryStream)) + { + _isSending = false; + return; + } + + await _clientWebSocket.SendAsync(new ArraySegment(memoryStream.GetBuffer(), 0, (int)memoryStream.Position), WebSocketMessageType.Binary, true, _cancellationTokenSource.Token); + + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene.TimerComponent.Net.Remove(ref _connectTimeoutId); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta new file mode 100644 index 00000000..cba0fb36 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2b829921d07d451ab3f103fd1b89d5b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs new file mode 100644 index 00000000..39373f1b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs @@ -0,0 +1,180 @@ +#if !FANTASY_NET && !FANTASY_CONSOLE +using System; +using System.Collections.Generic; +using System.IO; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +using UnityWebSocket; + +namespace Fantasy.Network.WebSocket +{ + // 因为webgl的限制、注定这个要是在游戏主线程里。所以这个库不会再其他线程执行的。 + // WebGL:在WebGL环境下运行 + // 另外不是运行在WebGL环境下,也没必要使用WebSocket协议了。完全可以使用TCP或KCP运行。同样也不会有那个队列产生的GC。 + public class WebSocketClientNetwork : AClientNetwork + { + private UnityWebSocket.WebSocket _webSocket; + private bool _isInnerDispose; + private bool _isConnected; + private long _connectTimeoutId; + private BufferPacketParser _packetParser; + private readonly Queue _messageCache = new Queue(); + + private Action _onConnectFail; + private Action _onConnectComplete; + private Action _onConnectDisconnect; + + public void Initialize(NetworkTarget networkTarget) + { + base.Initialize(NetworkType.Client, NetworkProtocolType.WebSocket, networkTarget); + _packetParser = PacketParserFactory.CreateClient(this); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + base.Dispose(); + + if (_webSocket != null && _webSocket.ReadyState != WebSocketState.Closed) + { + _onConnectDisconnect?.Invoke(); + _webSocket.CloseAsync(); + } + + _packetParser.Dispose(); + ClearConnectTimeout(); + _messageCache.Clear(); + } + + public override Session Connect(string remoteAddress, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + // 如果已经初始化过一次,抛出异常,要求重新实例化 + + if (IsInit) + { + throw new NotSupportedException($"WebSocketClientNetwork Id:{Id} Has already been initialized. If you want to call Connect again, please re instantiate it."); + } + + IsInit = true; + _onConnectFail = onConnectFail; + _onConnectComplete = onConnectComplete; + _onConnectDisconnect = onConnectDisconnect; + _connectTimeoutId = Scene.TimerComponent.Net.OnceTimer(connectTimeout, () => + { + _onConnectFail?.Invoke(); + Dispose(); + }); + var webSocketAddress = WebSocketHelper.GetWebSocketAddress(remoteAddress, isHttps); + _webSocket = new UnityWebSocket.WebSocket(webSocketAddress); + _webSocket.OnOpen += OnNetworkConnectComplete; + _webSocket.OnMessage += OnReceiveComplete; + _webSocket.OnClose += (sender, args) => + { + _onConnectDisconnect?.Invoke(); + Dispose(); + }; + _webSocket.ConnectAsync(); + Session = Session.Create(this, null); + return Session; + } + + private void OnNetworkConnectComplete(object sender, OpenEventArgs e) + { + if (IsDisposed) + { + return; + } + + _isConnected = true; + ClearConnectTimeout(); + _onConnectComplete?.Invoke(); + + while (_messageCache.TryDequeue(out var memoryStream)) + { + Send(memoryStream); + } + } + + #region Receive + + private void OnReceiveComplete(object sender, MessageEventArgs e) + { + try + { + // WebSocket 协议已经在协议层面处理了消息的边界问题,因此不需要额外的粘包处理逻辑。 + // 所以如果解包的时候出现任何错误只能是恶意攻击造成的。 + var rawDataLength = e.RawData.Length; + _packetParser.UnPack(e.RawData, ref rawDataLength, out var packInfo); + Session.Receive(packInfo); + } + catch (ScanException ex) + { + Log.Warning($"{ex}"); + Dispose(); + } + catch (Exception ex) + { + Log.Error($"{ex}"); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + if (IsDisposed) + { + return; + } + + var buffer = _packetParser.Pack(ref rpcId, ref routeId, memoryStream, message); + + if (!_isConnected) + { + _messageCache.Enqueue(buffer); + return; + } + + Send(buffer); + } + + private void Send(MemoryStreamBuffer memoryStream) + { + _webSocket.SendAsync(memoryStream.GetBuffer(), 0, (int)memoryStream.Position); +#if !UNITY_EDITOR && UNITY_WEBGL + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } +#endif + } + + #endregion + + public override void RemoveChannel(uint channelId) + { + Dispose(); + } + + private void ClearConnectTimeout() + { + if (_connectTimeoutId == 0) + { + return; + } + + Scene?.TimerComponent?.Net?.Remove(ref _connectTimeoutId); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta new file mode 100644 index 00000000..9f9f305f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Client/WebSocketClientNetworkWebgl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b52ea2d6356f484ba1a7a63bf549cce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server.meta new file mode 100644 index 00000000..2d32188a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ae9532d905102432da68c4ac0ded270a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs new file mode 100644 index 00000000..9bf1e87e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs @@ -0,0 +1,112 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +using System.Net; +using Fantasy.Async; +using Fantasy.Network.Interface; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable PossibleMultipleEnumeration +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Network.WebSocket; + +public class WebSocketServerNetwork : ANetwork +{ + private Random _random; + private HttpListener _httpListener; + private readonly Dictionary _connectionChannel = new Dictionary(); + + public void Initialize(NetworkTarget networkTarget, IEnumerable urls) + { + base.Initialize(NetworkType.Server, NetworkProtocolType.WebSocket, networkTarget); + + try + { + _random = new Random(); + _httpListener = new HttpListener(); + StartAcceptAsync(urls).Coroutine(); + Log.Info($"SceneConfigId = {Scene.SceneConfigId} WebSocketServer Listen {urls.FirstOrDefault()}"); + } + catch (HttpListenerException e) + { + if (e.ErrorCode == 5) + { + throw new Exception($"CMD管理员中输入: netsh http add urlacl url=http://*:8080/ user=Everyone", e); + } + + Log.Error(e); + } + catch (Exception e) + { + Log.Error(e); + } + } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + if (_httpListener != null) + { + _httpListener.Close(); + _httpListener = null; + } + + foreach (var channel in _connectionChannel.Values.ToArray()) + { + channel.Dispose(); + } + + _connectionChannel.Clear(); + base.Dispose(); + } + + private async FTask StartAcceptAsync(IEnumerable urls) + { + foreach (var prefix in urls) + { + _httpListener.Prefixes.Add(prefix); + } + _httpListener.Start(); + + while (!IsDisposed) + { + try + { + var httpListenerContext = await _httpListener.GetContextAsync(); + var webSocketContext = await httpListenerContext.AcceptWebSocketAsync(null); + var channelId = 0xC0000000 | (uint) _random.Next(); + + while (_connectionChannel.ContainsKey(channelId)) + { + channelId = 0xC0000000 | (uint) _random.Next(); + } + + _connectionChannel.Add(channelId, new WebSocketServerNetworkChannel(this, channelId, webSocketContext, httpListenerContext.Request.RemoteEndPoint)); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void RemoveChannel(uint channelId) + { + if (IsDisposed || !_connectionChannel.Remove(channelId, out var channel)) + { + return; + } + + if (channel.IsDisposed) + { + return; + } + + channel.Dispose(); + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta new file mode 100644 index 00000000..6b617242 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetwork.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1a965026757445edbe7433d9acb1d02 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs new file mode 100644 index 00000000..23c0d65c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs @@ -0,0 +1,247 @@ +#if FANTASY_NET +using System.Buffers; +using System.IO.Pipelines; +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; +using Fantasy.Async; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.Serialize; +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Network.WebSocket; + +public sealed class WebSocketServerNetworkChannel : ANetworkServerChannel +{ + private bool _isSending; + private bool _isInnerDispose; + private readonly Pipe _pipe = new Pipe(); + private readonly System.Net.WebSockets.WebSocket _webSocket; + private readonly WebSocketServerNetwork _network; + private readonly ReadOnlyMemoryPacketParser _packetParser; + private readonly Queue _sendBuffers = new Queue(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + public WebSocketServerNetworkChannel(ANetwork network, uint id, HttpListenerWebSocketContext httpListenerWebSocketContext, IPEndPoint remoteEndPoint) : base(network, id, remoteEndPoint) + { + _network = (WebSocketServerNetwork)network; + _webSocket = httpListenerWebSocketContext.WebSocket; + _packetParser = PacketParserFactory.CreateServerReadOnlyMemoryPacket(network); + ReadPipeDataAsync().Coroutine(); + ReceiveSocketAsync().Coroutine(); + } + + public override void Dispose() + { + if (IsDisposed || _isInnerDispose) + { + return; + } + + _isInnerDispose = true; + if (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + _cancellationTokenSource.Cancel(); + } + catch (OperationCanceledException) + { + // 通常情况下,此处的异常可以忽略 + } + } + _sendBuffers.Clear(); + _network.RemoveChannel(Id); + base.Dispose(); + _webSocket.Dispose(); + _isSending = false; + } + + #region ReceiveSocket + + private async FTask ReceiveSocketAsync() + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + try + { + var memory = _pipe.Writer.GetMemory(8192); + // 这里接收的数据不一定是一个完整的包。如果大于8192就会分成多个包。 + var receiveResult = await _webSocket.ReceiveAsync(memory, _cancellationTokenSource.Token); + + if (receiveResult.MessageType == WebSocketMessageType.Close) + { + break; + } + + var count = receiveResult.Count; + + if (count > 0) + { + await PipeWriterFlushAsync(count); + } + } + catch (OperationCanceledException) + { + break; + } + catch (ObjectDisposedException) + { + Dispose(); + break; + } + catch (WebSocketException) + { + // Log.Error($"WebSocket error: {wse.Message}"); + Dispose(); + break; + } + catch (Exception e) + { + Log.Error(e); + } + } + + await _pipe.Writer.CompleteAsync(); + } + + private async FTask PipeWriterFlushAsync(int count) + { + _pipe.Writer.Advance(count); + await _pipe.Writer.FlushAsync(); + } + + #endregion + + #region ReceivePipeData + + private async FTask ReadPipeDataAsync() + { + var pipeReader = _pipe.Reader; + while (!_cancellationTokenSource.IsCancellationRequested) + { + ReadResult result = default; + + try + { + result = await pipeReader.ReadAsync(_cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + // 出现这个异常表示取消了_cancellationTokenSource。一般Channel断开会取消。 + break; + } + + var buffer = result.Buffer; + var consumed = buffer.Start; + var examined = buffer.End; + + while (TryReadMessage(ref buffer, out var message)) + { + ReceiveData(ref message); + consumed = buffer.Start; + } + + if (result.IsCompleted) + { + break; + } + + pipeReader.AdvanceTo(consumed, examined); + } + + await pipeReader.CompleteAsync(); + } + + private bool TryReadMessage(ref ReadOnlySequence buffer, out ReadOnlyMemory message) + { + if (buffer.Length == 0) + { + message = default; + return false; + } + + message = buffer.First; + + if (message.Length == 0) + { + message = default; + return false; + } + + buffer = buffer.Slice(message.Length); + return true; + } + + private void ReceiveData(ref ReadOnlyMemory buffer) + { + try + { + while (_packetParser.UnPack(ref buffer, out var packInfo)) + { + if (_cancellationTokenSource.IsCancellationRequested) + { + return; + } + + Session.Receive(packInfo); + } + } + catch (ScanException e) + { + Log.Warning($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + catch (Exception e) + { + Log.Error($"RemoteAddress:{RemoteEndPoint} \n{e}"); + Dispose(); + } + } + + #endregion + + #region Send + + public override void Send(uint rpcId, long routeId, MemoryStreamBuffer memoryStream, IMessage message) + { + _sendBuffers.Enqueue(_packetParser.Pack(ref rpcId, ref routeId, memoryStream, message)); + + if (!_isSending) + { + Send().Coroutine(); + } + } + + private async FTask Send() + { + if (_isSending || IsDisposed) + { + return; + } + + _isSending = true; + + while (_isSending) + { + if (!_sendBuffers.TryDequeue(out var memoryStream)) + { + _isSending = false; + return; + } + + await _webSocket.SendAsync(new ArraySegment(memoryStream.GetBuffer(), 0, (int)memoryStream.Position), WebSocketMessageType.Binary, true, _cancellationTokenSource.Token); + + if (memoryStream.MemoryStreamBufferSource == MemoryStreamBufferSource.Pack) + { + _network.MemoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + } + } + + #endregion +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta new file mode 100644 index 00000000..b6604164 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Protocol/WebSocket/Server/WebSocketServerNetworkChannel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d353b9b1e0e2940cb8b519317d26b7c7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route.meta new file mode 100644 index 00000000..4c6733b3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7214c9850b6e5412d920a3db65416738 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route/RouteComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route/RouteComponent.cs new file mode 100644 index 00000000..ba00addc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route/RouteComponent.cs @@ -0,0 +1,65 @@ +using Fantasy.Entitas; + +#if FANTASY_NET +namespace Fantasy.Network; + +/// +/// 自定义Route组件、如果要自定义Route协议必须使用这个组件 +/// +public sealed class RouteComponent : Entity +{ + /// + /// 存储路由类型和路由ID的映射关系。 + /// + public readonly Dictionary RouteAddress = new Dictionary(); + + /// + /// 添加路由类型和路由ID的映射关系。 + /// + /// 路由类型。 + /// 路由ID。 + public void AddAddress(long routeType, long routeId) + { + RouteAddress.Add(routeType, routeId); + } + + /// + /// 移除指定路由类型的映射关系。 + /// + /// 路由类型。 + public void RemoveAddress(long routeType) + { + RouteAddress.Remove(routeType); + } + + /// + /// 获取指定路由类型的路由ID。 + /// + /// 路由类型。 + /// 路由ID。 + public long GetRouteId(long routeType) + { + return RouteAddress.GetValueOrDefault(routeType, 0); + } + + /// + /// 尝试获取指定路由类型的路由ID。 + /// + /// 路由类型。 + /// 输出的路由ID。 + /// 如果获取成功返回true,否则返回false。 + public bool TryGetRouteId(long routeType, out long routeId) + { + return RouteAddress.TryGetValue(routeType, out routeId); + } + + /// + /// 释放组件资源,清空映射关系。 + /// + public override void Dispose() + { + RouteAddress.Clear(); + base.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route/RouteComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route/RouteComponent.cs.meta new file mode 100644 index 00000000..ce869a47 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Route/RouteComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 061c0d492751d4ca695e8ce5dff4253e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session.meta new file mode 100644 index 00000000..6387ffac --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: caade9c96d7c84a1986570594ae5f5ec +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component.meta new file mode 100644 index 00000000..f74fe289 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 913e8547caf3843af95a4b3325cb03db +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs new file mode 100644 index 00000000..dc4677ef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs @@ -0,0 +1,156 @@ +// ReSharper disable MemberCanBePrivate.Global + +#if FANTASY_CONSOLE + +using System; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.InnerMessage; +using Fantasy.Timer; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Network +{ + public class SessionHeartbeatComponentAwakeSystem : AwakeSystem + { + protected override void Awake(SessionHeartbeatComponent self) + { + self.TimerComponent = self.Scene.TimerComponent; + } + } + + /// + /// 负责管理会话心跳的组件。 + /// + public class SessionHeartbeatComponent : Entity + { + public int TimeOut; + public long TimerId; + public long LastTime; + public long SelfRunTimeId; + public long TimeOutTimerId; + public long SessionRunTimeId; + public TimerComponent TimerComponent; + public EntityReference Session; + private readonly PingRequest _pingRequest = new PingRequest(); + + public int Ping { get; private set; } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + Stop(); + Ping = 0; + Session = null; + TimeOut = 0; + SelfRunTimeId = 0; + base.Dispose(); + } + + /// + /// 使用指定的间隔启动心跳功能。 + /// + /// 以毫秒为单位的心跳请求发送间隔。 + /// 设置与服务器的通信超时时间,如果超过这个时间限制,将自动断开会话(Session)。 + /// 用于检测与服务器连接超时频率。 + public void Start(int interval, int timeOut = 2000, int timeOutInterval = 3000) + { + TimeOut = timeOut + interval; + Session = (Session)Parent; + SelfRunTimeId = RuntimeId; + LastTime = TimeHelper.Now; + + if (TimerComponent == null) + { + Log.Error("请在Unity的菜单执行Fantasy->Generate link.xml再重新打包"); + return; + } + + TimerId = TimerComponent.Net.RepeatedTimer(interval, () => RepeatedSend().Coroutine()); + TimeOutTimerId = TimerComponent.Net.RepeatedTimer(timeOutInterval, CheckTimeOut); + } + + private void CheckTimeOut() + { + if (TimeHelper.Now - LastTime < TimeOut) + { + return; + } + + Session entityReference = Session; + + if (entityReference == null) + { + return; + } + + entityReference.Dispose(); + } + + /// + /// 停止心跳功能。 + /// + public void Stop() + { + if (TimerId != 0) + { + TimerComponent?.Net.Remove(ref TimerId); + } + + if (TimeOutTimerId != 0) + { + TimerComponent?.Net.Remove(ref TimeOutTimerId); + } + } + + /// + /// 异步发送心跳请求并处理响应。 + /// + /// 表示进行中操作的异步任务。 + private async FTask RepeatedSend() + { + if (SelfRunTimeId != RuntimeId) + { + Stop(); + return; + } + + Session session = Session; + + if (session == null) + { + Dispose(); + return; + } + + try + { + var requestTime = TimeHelper.Now; + + var pingResponse = (PingResponse)await session.Call(_pingRequest); + + if (pingResponse.ErrorCode != 0) + { + return; + } + + var responseTime = TimeHelper.Now; + LastTime = responseTime; + Ping = (int)(responseTime - requestTime) / 2; + TimeHelper.TimeDiff = pingResponse.Now + Ping - responseTime; + } + catch (Exception) + { + Dispose(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta new file mode 100644 index 00000000..c71229b4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/ConsoleSessionHeartbeatComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 99fb296c5f69d491d9c4d0450f42318f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs new file mode 100644 index 00000000..1edc1cf9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs @@ -0,0 +1,104 @@ +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Timer; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if FANTASY_NET +namespace Fantasy.Network; + +public class SessionIdleCheckerComponentAwakeSystem : AwakeSystem +{ + protected override void Awake(SessionIdleCheckerComponent self) + { + self.TimerComponent = self.Scene.TimerComponent; + } +} + +/// +/// 负责检查会话空闲超时的组件。 +/// +public class SessionIdleCheckerComponent : Entity +{ + /// + /// 空闲超时时间(毫秒) + /// + private long _timeOut; + /// + /// 检查计时器的 ID + /// + private long _timerId; + /// + /// 用于确保组件完整性的自身运行时 ID + /// + private long _selfRuntimeId; + /// + /// 对会话对象的引用 + /// + private Session _session; + public TimerComponent TimerComponent; + + /// + /// 重写 Dispose 方法以释放资源。 + /// + public override void Dispose() + { + Stop(); // 停止检查计时器 + _timeOut = 0; // 重置空闲超时时间 + _selfRuntimeId = 0; // 重置自身运行时 ID + _session = null; // 清除会话引用 + base.Dispose(); + } + + /// + /// 使用指定的间隔和空闲超时时间启动空闲检查功能。 + /// + /// 以毫秒为单位的检查间隔。 + /// 以毫秒为单位的空闲超时时间。 + public void Start(int interval, int timeOut) + { + _timeOut = timeOut; + _session = (Session)Parent; + _selfRuntimeId = RuntimeId; + // 安排重复计时器,在指定的间隔内执行 Check 方法 + _timerId = TimerComponent.Net.RepeatedTimer(interval, Check); + } + + /// + /// 停止空闲检查功能。 + /// + public void Stop() + { + if (_timerId == 0) + { + return; + } + + TimerComponent.Net.Remove(ref _timerId); + } + + /// + /// 执行空闲检查操作。 + /// + private void Check() + { + if (_selfRuntimeId != RuntimeId || IsDisposed || _session == null) + { + Stop(); + return; + } + + var timeNow = TimeHelper.Now; + + if (timeNow - _session.LastReceiveTime < _timeOut) + { + return; + } + + Log.Warning($"session timeout id:{Id} timeNow:{timeNow} _session.LastReceiveTime:{_session.LastReceiveTime} _timeOut:{_timeOut}"); + _session.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta new file mode 100644 index 00000000..8eae6c8f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/SessionIdleCheckerComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6536d2ffd3214fdf87a649ad0914c90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs new file mode 100644 index 00000000..e657963c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs @@ -0,0 +1,157 @@ +// ReSharper disable MemberCanBePrivate.Global + +using System; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.InnerMessage; +using Fantasy.Timer; + +#if FANTASY_UNITY + +namespace Fantasy.Network +{ + public class SessionHeartbeatComponentAwakeSystem : AwakeSystem + { + protected override void Awake(SessionHeartbeatComponent self) + { + self.TimerComponent = self.Scene.TimerComponent; + } + } + + /// + /// 负责管理会话心跳的组件。 + /// + public class SessionHeartbeatComponent : Entity + { + public int TimeOut; + public long TimerId; + public long LastTime; + public long SelfRunTimeId; + public long TimeOutTimerId; + public TimerComponent TimerComponent; + public EntityReference Session; + private readonly PingRequest _pingRequest = new PingRequest(); + + public int Ping { get; private set; } + + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + Stop(); + Ping = 0; + Session = null; + TimeOut = 0; + LastTime = 0; + SelfRunTimeId = 0; + base.Dispose(); + } + + /// + /// 使用指定的间隔启动心跳功能。 + /// + /// 以毫秒为单位的心跳请求发送间隔。 + /// 设置与服务器的通信超时时间,如果超过这个时间限制,将自动断开会话(Session)。 + /// 用于检测与服务器连接超时频率。 + public void Start(int interval, int timeOut = 5000, int timeOutInterval = 3000) + { + TimeOut = timeOut + interval; + Session = (Session)Parent; + SelfRunTimeId = RuntimeId; + LastTime = TimeHelper.Now; + + if (TimerComponent == null) + { + Log.Error("请在Unity的菜单执行Fantasy->Generate link.xml再重新打包"); + return; + } + + TimerId = TimerComponent.Unity.RepeatedTimer(interval, () => + { + RepeatedSend().Forget(); + }); + TimeOutTimerId = TimerComponent.Unity.RepeatedTimer(timeOutInterval, CheckTimeOut); + } + + private void CheckTimeOut() + { + if (TimeHelper.Now - LastTime < TimeOut) + { + return; + } + + Session entityReference = Session; + + if (entityReference == null) + { + return; + } + + entityReference.Dispose(); + } + + /// + /// 停止心跳功能。 + /// + public void Stop() + { + if (TimerId != 0) + { + TimerComponent?.Unity.Remove(ref TimerId); + } + + if (TimeOutTimerId != 0) + { + TimerComponent?.Unity.Remove(ref TimeOutTimerId); + } + } + + /// + /// 异步发送心跳请求并处理响应。 + /// + /// 表示进行中操作的异步任务。 + private async UniTask RepeatedSend() + { + if (SelfRunTimeId != RuntimeId) + { + Stop(); + return; + } + + Session session = Session; + + if (session == null) + { + Dispose(); + return; + } + + try + { + var requestTime = TimeHelper.Now; + var pingResponse = (PingResponse)await session.Call(_pingRequest); + + if (pingResponse.ErrorCode != 0) + { + return; + } + + var responseTime = TimeHelper.Now; + LastTime = responseTime; + Ping = (int)(responseTime - requestTime) / 2; + TimeHelper.TimeDiff = pingResponse.Now + Ping - responseTime; + } + catch (Exception) + { + Dispose(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta new file mode 100644 index 00000000..47491106 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Component/UnitySessionHeartbeatComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 457cbbb00597a4a50b1ff761ccd0335a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession.meta new file mode 100644 index 00000000..361739ca --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c344eba409d3d479295fec3e198e0376 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessScheduler.cs new file mode 100644 index 00000000..2036dc4e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessScheduler.cs @@ -0,0 +1,263 @@ +#if FANTASY_NET +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +using System.Runtime.CompilerServices; +using Fantasy.IdFactory; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Platform.Net; +using Fantasy.Serialize; + +namespace Fantasy.Scheduler; + +internal static class ProcessScheduler +{ + public static void Scheduler(this ProcessSession session, Type messageType, uint rpcId, long routeId, APackInfo packInfo) + { + switch (packInfo.OpCodeIdStruct.Protocol) + { + case OpCodeType.InnerResponse: + case OpCodeType.InnerRouteResponse: + case OpCodeType.InnerAddressableResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + { + using (packInfo) + { + var sessionScene = session.Scene; + var message = packInfo.Deserialize(messageType); + sessionScene.ThreadSynchronizationContext.Post(() => + { + // 因为有可能是其他Scene线程下发送过来的、所以必须放到当前Scene进程下运行。 + sessionScene.NetworkMessagingComponent.ResponseHandler(rpcId, (IResponse)message); + }); + } + + return; + } + case OpCodeType.InnerRouteMessage: + { + using (packInfo) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var message = packInfo.Deserialize(messageType); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, message, rpcId).Coroutine(); + }); + } + + return; + } + case OpCodeType.InnerRouteRequest: + { + using (packInfo) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var message = packInfo.Deserialize(messageType); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + sceneMessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, rpcId); + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, message, rpcId).Coroutine(); + }); + } + + return; + } + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterCustomRouteMessage: + case OpCodeType.OuterAddressableRequest: + case OpCodeType.OuterCustomRouteRequest: + { + using (packInfo) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new NotSupportedException($"not found scene routeId = {routeId}"); + } + + var message = packInfo.Deserialize(messageType); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + + if (entity == null || entity.IsDisposed) + { + scene.MessageDispatcherComponent.FailRouteResponse(session, messageType, InnerErrorCode.ErrNotFoundRoute, rpcId); + return; + } + + scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, message, rpcId).Coroutine(); + }); + } + return; + } + default: + { + var packInfoProtocolCode = packInfo.ProtocolCode; + packInfo.Dispose(); + throw new NotSupportedException($"SessionInnerScheduler Received unsupported message protocolCode:{packInfoProtocolCode} messageType:{messageType}"); + } + } + } + + public static void Scheduler(this ProcessSession session, Type messageType, uint rpcId, long routeId, uint protocolCode, object message) + { + OpCodeIdStruct opCodeIdStruct = protocolCode; + + switch (opCodeIdStruct.Protocol) + { + case OpCodeType.InnerResponse: + case OpCodeType.InnerRouteResponse: + case OpCodeType.InnerAddressableResponse: + case OpCodeType.OuterAddressableResponse: + case OpCodeType.OuterCustomRouteResponse: + { + var sessionScene = session.Scene; + sessionScene.ThreadSynchronizationContext.Post(() => + { + var iResponse = (IResponse)session.Deserialize(messageType, message, ref opCodeIdStruct); + // 因为有可能是其他Scene线程下发送过来的、所以必须放到当前Scene进程下运行。 + sessionScene.NetworkMessagingComponent.ResponseHandler(rpcId, iResponse); + }); + + return; + } + case OpCodeType.InnerAddressableMessage: + case OpCodeType.InnerRouteMessage: + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var messageObject = session.Deserialize(messageType, message, ref opCodeIdStruct); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, messageObject, rpcId).Coroutine(); + }); + + return; + } + case OpCodeType.InnerAddressableRequest: + case OpCodeType.InnerRouteRequest: + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + throw new Exception($"not found scene routeId:{routeId}"); + } + + var messageObject = session.Deserialize(messageType, message, ref opCodeIdStruct); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + var sceneMessageDispatcherComponent = scene.MessageDispatcherComponent; + + if (entity == null || entity.IsDisposed) + { + sceneMessageDispatcherComponent.FailRouteResponse(session, message.GetType(), InnerErrorCode.ErrNotFoundRoute, rpcId); + return; + } + + sceneMessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, messageObject, rpcId).Coroutine(); + }); + + return; + } + case OpCodeType.OuterAddressableMessage: + case OpCodeType.OuterCustomRouteMessage: + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + + if (!Process.TryGetScene(sceneId, out var scene)) + { + Log.Error($"not found scene routeId:{routeId}"); + return; + } + + var messageObject = session.Deserialize(messageType, message, ref opCodeIdStruct); + + scene.ThreadSynchronizationContext.Post(() => + { + var entity = scene.GetEntity(routeId); + + switch (entity) + { + case null: + { + // 执行到这里是说明Session已经断开了 + // 因为这里是其他服务器Send到外网的数据、所以不需要给发送端返回就可以 + return; + } + case Session gateSession: + { + // 这里如果是Session只可能是Gate的Session、如果是的话、肯定是转发Address消息 + gateSession.Send((IMessage)messageObject, rpcId); + return; + } + default: + { + scene.MessageDispatcherComponent.RouteMessageHandler(session, messageType, entity, messageObject, rpcId).Coroutine(); + return; + } + } + }); + + return; + } + default: + { + throw new NotSupportedException($"SessionInnerScheduler Received unsupported message protocolCode:{protocolCode} messageType:{messageType}"); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta new file mode 100644 index 00000000..269c511b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a88ea22f28c7247039d360c1139b976e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSession.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSession.cs new file mode 100644 index 00000000..f576673e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSession.cs @@ -0,0 +1,125 @@ +using Fantasy.Async; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Pool; +using Fantasy.Scheduler; +using Fantasy.Serialize; +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8603 // Possible null reference return. + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#if FANTASY_NET +namespace Fantasy.Network; + +/// +/// 网络服务器内部会话。 +/// +public sealed class ProcessSession : Session +{ + private readonly MemoryStreamBufferPool _memoryStreamBufferPool = new MemoryStreamBufferPool(); + private readonly Dictionary> _createInstances = new Dictionary>(); + + /// + /// 发送消息到服务器内部。 + /// + /// 要发送的消息。 + /// RPC 标识符。 + /// 路由标识符。 + public override void Send(IMessage message, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + this.Scheduler(message.GetType(), rpcId, routeId, message.OpCode(), message); + } + + /// + /// 发送路由消息到服务器内部。 + /// + /// 要发送的路由消息。 + /// RPC 标识符。 + /// 路由标识符。 + public override void Send(IRouteMessage routeMessage, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + this.Scheduler(routeMessage.GetType(), rpcId, routeId, routeMessage.OpCode(), routeMessage); + } + + public override void Send(uint rpcId, long routeId, Type messageType, APackInfo packInfo) + { + if (IsDisposed) + { + return; + } + + this.Scheduler(messageType, rpcId, routeId, packInfo); + } + + public override void Send(ProcessPackInfo packInfo, uint rpcId = 0, long routeId = 0) + { + this.Scheduler(packInfo.MessageType, rpcId, routeId, packInfo); + } + + public override void Send(MemoryStreamBuffer memoryStream, uint rpcId = 0, long routeId = 0) + { + throw new Exception("The use of this method is not supported"); + } + + public override FTask Call(IRouteRequest request, long routeId = 0) + { + throw new Exception("The use of this method is not supported"); + } + + public override FTask Call(IRequest request, long routeId = 0) + { + throw new Exception("The use of this method is not supported"); + } + + public object Deserialize(Type messageType, object message, ref OpCodeIdStruct opCodeIdStruct) + { + var memoryStream = _memoryStreamBufferPool.RentMemoryStream(MemoryStreamBufferSource.None); + + try + { + if (SerializerManager.TryGetSerializer(opCodeIdStruct.OpCodeProtocolType, out var serializer)) + { + serializer.Serialize(messageType, message, memoryStream); + + if (memoryStream.Position == 0) + { + if (_createInstances.TryGetValue(messageType, out var createInstance)) + { + return createInstance(); + } + + createInstance = CreateInstance.CreateObject(messageType); + _createInstances.Add(messageType, createInstance); + return createInstance(); + } + + memoryStream.SetLength(memoryStream.Position); + memoryStream.Seek(0, SeekOrigin.Begin); + return serializer.Deserialize(messageType, memoryStream); + } + } + catch (Exception e) + { + Log.Error($"ProcessSession.Deserialize {e}"); + } + finally + { + _memoryStreamBufferPool.ReturnMemoryStream(memoryStream); + } + + throw new Exception($"type:{messageType} Does not support processing protocol"); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta new file mode 100644 index 00000000..6d2ab0ed --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSession.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: af272d9643ac74c4dad1cf580f9f6ba6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs new file mode 100644 index 00000000..6e3a534f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs @@ -0,0 +1,17 @@ +using Fantasy.Network.Interface; + +#if FANTASY_NET +namespace Fantasy.Network; + +internal sealed class ProcessSessionInfo(Session session, AClientNetwork aClientNetwork) : IDisposable +{ + public readonly Session Session = session; + public readonly AClientNetwork AClientNetwork = aClientNetwork; + + public void Dispose() + { + Session.Dispose(); + AClientNetwork?.Dispose(); + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta new file mode 100644 index 00000000..b4df6820 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/ProcessSession/ProcessSessionInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 95db8925726a34b0dae70295cbd646f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Session.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Session.cs new file mode 100644 index 00000000..b41944f0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Session.cs @@ -0,0 +1,262 @@ +// ReSharper disable RedundantUsingDirective +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Entitas.Interface; +using Fantasy.Helper; +using Fantasy.Network.Interface; +using Fantasy.PacketParser; +using Fantasy.PacketParser.Interface; +using Fantasy.Scheduler; +using Fantasy.Serialize; +#if FANTASY_NET +using Fantasy.Platform.Net; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#endif +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 +#pragma warning disable CS8601 +#pragma warning disable CS8618 + +namespace Fantasy.Network +{ + /// + /// 网络会话的基类,用于管理网络通信。 + /// + public class Session : Entity, ISupportedMultiEntity + { + private uint _rpcId; + internal long LastReceiveTime; + /// + /// 关联的网络连接通道 + /// + public INetworkChannel Channel { get; private set; } + /// + /// 当前Session的终结点信息 + /// + public IPEndPoint RemoteEndPoint { get; private set; } + private ANetworkMessageScheduler NetworkMessageScheduler { get; set;} + public readonly Dictionary> RequestCallback = new(); + /// + /// Session的Dispose委托 + /// + public event Action OnDispose; +#if FANTASY_NET + internal static Session Create(ANetworkMessageScheduler networkMessageScheduler, ANetworkServerChannel channel, NetworkTarget networkTarget) + { + var session = Entity.Create(channel.Scene, false, true); + session.Channel = channel; + session.NetworkMessageScheduler = networkMessageScheduler; + session.RemoteEndPoint = channel.RemoteEndPoint as IPEndPoint; + session.OnDispose = channel.Dispose; + session.LastReceiveTime = TimeHelper.Now; + // 在外部网络目标下,添加会话空闲检查组件 + if (networkTarget == NetworkTarget.Outer) + { + var interval = ProcessDefine.SessionIdleCheckerInterval; + var timeOut = ProcessDefine.SessionIdleCheckerTimeout; + session.AddComponent().Start(interval, timeOut); + } + return session; + } +#endif + internal static Session Create(AClientNetwork network, IPEndPoint remoteEndPoint) + { + // 创建会话实例 + var session = Entity.Create(network.Scene, false, true); + session.Channel = network; + session.RemoteEndPoint = remoteEndPoint; + session.OnDispose = network.Dispose; + session.NetworkMessageScheduler = network.NetworkMessageScheduler; + session.LastReceiveTime = TimeHelper.Now; + return session; + } +#if FANTASY_NET + internal static ProcessSession CreateInnerSession(Scene scene) + { + var session = Entity.Create(scene, false, false); + session.NetworkMessageScheduler = new InnerMessageScheduler(scene); + return session; + } + + /// + /// 发送一个消息,框架内部使用建议不要用这个方法。 + /// + /// 如果是RPC消息需要传递一个RPCId + /// routeId + /// 消息的类型 + /// packInfo消息包 + public virtual void Send(uint rpcId, long routeId, Type messageType, APackInfo packInfo) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, packInfo.MemoryStream, null); + } + + /// + /// 发送一个消息,框架内部使用建议不要用这个方法。 + /// + /// 一个ProcessPackInfo消息包 + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(ProcessPackInfo packInfo, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + using (packInfo) + { + Channel.Send(rpcId, routeId, packInfo.MemoryStream, null); + } + } + + /// + /// 发送一个消息 + /// + /// 需要发送的MemoryStreamBuffer + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(MemoryStreamBuffer memoryStream, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, memoryStream, null); + } +#endif + /// + /// 销毁一个Session,当执行了这个方法会自动断开网络的连接。 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + _rpcId = 0; + LastReceiveTime = 0; + Channel = null; + RemoteEndPoint = null; + NetworkMessageScheduler = null; + base.Dispose(); + + // 终止所有等待中的请求回调 + foreach (var requestCallback in RequestCallback.Values.ToArray()) + { + requestCallback.TrySetException(new Exception($"session is dispose: {Id}")); + } + + RequestCallback.Clear(); + OnDispose?.Invoke(); + } + + /// + /// 发送一个消息 + /// + /// 消息的实例 + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(IMessage message, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, null, message); + } + + /// + /// 发送一个消息 + /// + /// 消息的实例,不同的是这个是发送Route消息使用的 + /// 如果是RPC消息需要传递一个RPCId + /// routeId + public virtual void Send(IRouteMessage routeMessage, uint rpcId = 0, long routeId = 0) + { + if (IsDisposed) + { + return; + } + + Channel.Send(rpcId, routeId, null, routeMessage); + } + + /// + /// 发送一个RPC消息 + /// + /// 请求Route消息的实例 + /// routeId + /// + public virtual UniTask Call(IRouteRequest request, long routeId = 0) + { + if (IsDisposed) + { + return default; + } + var requestCallback = AutoResetUniTaskCompletionSourcePlus.Create(); + var rpcId = ++_rpcId; + RequestCallback.Add(rpcId, requestCallback); + Send(request, rpcId, routeId); + return requestCallback.Task; + } + + /// + /// 发送一个RPC消息 + /// + /// 请求消息的实例 + /// routeId + /// + public virtual UniTask Call(IRequest request, long routeId = 0) + { + if (IsDisposed) + { + return default; + } + + var requestCallback = AutoResetUniTaskCompletionSourcePlus.Create(); + var rpcId = ++_rpcId; + RequestCallback.Add(rpcId, requestCallback); + Send(request, rpcId, routeId); + return requestCallback.Task; + } + + internal void Receive(APackInfo packInfo) + { + if (IsDisposed) + { + return; + } + + LastReceiveTime = TimeHelper.Now; + + try + { + NetworkMessageScheduler.Scheduler(this, packInfo); + } + catch (Exception e) + { + // 如果解析失败,只有一种可能,那就是有人恶意发包。 + // 所以这里强制关闭了当前连接。不让对方一直发包。 + Dispose(); + Log.Error(e); + } + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Session.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Session.cs.meta new file mode 100644 index 00000000..ad17a412 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Network/Session/Session.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5376c3723b02540d4955f019e0826a7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform.meta new file mode 100644 index 00000000..282ef97d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 534116af9a7e44a71abe399bf23f89bb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console.meta new file mode 100644 index 00000000..251090e1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bbb39d4a6a48a4fd1a301afe2b382364 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/Entry.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/Entry.cs new file mode 100644 index 00000000..3f461326 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/Entry.cs @@ -0,0 +1,101 @@ +#if FANTASY_CONSOLE +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Serialize; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Console +{ + public struct OnFantasyInit + { + public Scene Scene; + } + + /// + /// 一般的控制台启动入口,可以适用大部分客户端环境 + /// + public sealed class Entry + { + private static bool _isInit; + private static Thread _updateThread; + public static Scene Scene { get; private set; } + + /// + /// 初始化框架 + /// + /// + public static void Initialize(params System.Reflection.Assembly[] assemblies) + { + if (_isInit) + { + Log.Error("Fantasy has already been initialized and does not need to be initialized again!"); + return; + } + + // 初始化程序集管理系统 + AssemblySystem.Initialize(assemblies); + // 初始化序列化 + SerializerManager.Initialize(); + _isInit = true; + Log.Debug("Fantasy Initialize Complete!"); + } + + /// + /// 启动框架。 + /// 如果您的平台有每帧更新逻辑的方法,请不要调用这个方法。 + /// 如果没有实现每帧执行方法平台需要调用这个方法,目的是开启一个新的线程来每帧执行Update。 + /// 注意因为开启了一个新的线程来处理更新逻辑,所以要注意多线程的问题。 + /// + public static void StartUpdate() + { + _updateThread = new Thread(() => + { + while (_isInit) + { + ThreadScheduler.Update(); + Thread.Sleep(1); + } + }) + { + IsBackground = true + }; + _updateThread.Start(); + } + + /// + /// 在Entry中创建一个Scene,如果Scene已经被创建过,将先销毁Scene再创建。 + /// + /// + /// + public static async FTask CreateScene(string sceneRuntimeType = SceneRuntimeType.MainThread) + { + Scene?.Dispose(); + Scene = await Scene.Create(sceneRuntimeType); + await Scene.EventComponent.PublishAsync(new OnFantasyInit() + { + Scene = Scene + }); + return Scene; + } + + /// + /// 如果有的话一定要在每帧执行这个方法 + /// + public void Update() + { + ThreadScheduler.Update(); + } + + public static void Dispose() + { + AssemblySystem.Dispose(); + SerializerManager.Dispose(); + Scene?.Dispose(); + Scene = null; + _isInit = false; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/Entry.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/Entry.cs.meta new file mode 100644 index 00000000..3da7a479 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/Entry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc5c1ff7d14644495988c787b94e4221 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/ThreadSynchronizationContext.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/ThreadSynchronizationContext.cs new file mode 100644 index 00000000..29fd54ac --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/ThreadSynchronizationContext.cs @@ -0,0 +1,38 @@ +#if FANTASY_CONSOLE +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8765 // Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes). +namespace Fantasy +{ + public sealed class ThreadSynchronizationContext : SynchronizationContext + { + private Action _actionHandler; + private readonly Queue _queue = new(); + + public void Update() + { + while (_queue.TryDequeue(out _actionHandler)) + { + try + { + _actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + public void Post(Action action) + { + _queue.Enqueue(action); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta new file mode 100644 index 00000000..e152d90e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Console/ThreadSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48741dacd26f742bfb9f33dd96105ab6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net.meta new file mode 100644 index 00000000..c47d3c74 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f5923944e3cd54cbe8935ea06d2478c7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable.meta new file mode 100644 index 00000000..2dd25b5c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53cf00bfe984149d9872dc9d2d337fc9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/MachineConfig.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/MachineConfig.cs new file mode 100644 index 00000000..e09b00e7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/MachineConfig.cs @@ -0,0 +1,88 @@ +#if FANTASY_NET +// ReSharper disable InconsistentNaming +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.Helper; +using Newtonsoft.Json; +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net +{ + /// + /// 用于记录服务器物理信息 + /// + public sealed class MachineConfigData + { + /// + /// 存放所有MachineConfigInfo信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + /// + /// 获得MachineConfig的实例 + /// + public static MachineConfigData Instance { get; private set; } + /// + /// 初始化MachineConfig + /// + /// + public static void Initialize(string machineConfigJson) + { + Instance = machineConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + Instance._configs.TryAdd(config.Id, config); + } + } + /// + /// 根据Id获取MachineConfig + /// + /// + /// + /// + public MachineConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var machineConfigInfo)) + { + return machineConfigInfo; + } + + throw new FileNotFoundException($"MachineConfig not find {id} Id"); + } + /// + /// 根据Id获取MachineConfig + /// + /// + /// + /// + public bool TryGet(uint id, out MachineConfig config) + { + return _configs.TryGetValue(id, out config); + } + } + /// + /// 表示一个物理服务器的信息 + /// + public sealed class MachineConfig + { + /// + /// Id + /// + public uint Id { get; set; } + /// + /// 外网IP + /// + public string OuterIP { get; set; } + /// + /// 外网绑定IP + /// + public string OuterBindIP { get; set; } + /// + /// 内网绑定IP + /// + public string InnerBindIP { get; set; } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta new file mode 100644 index 00000000..a5fcd9af --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/MachineConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd753001cdd384069a959115f6ca365b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/ProcessConfig.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/ProcessConfig.cs new file mode 100644 index 00000000..4a400b07 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/ProcessConfig.cs @@ -0,0 +1,100 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.Helper; +using Newtonsoft.Json; +// ReSharper disable CollectionNeverUpdated.Global +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Platform.Net +{ + /// + /// 用于管理进程信息 + /// + public sealed class ProcessConfigData + { + /// + /// 存放所有ProcessConfig信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + /// + /// 获得ProcessConfigData的实例 + /// + public static ProcessConfigData Instance { get; private set; } + /// + /// 初始化MachineConfig + /// + /// + public static void Initialize(string processConfigJson) + { + Instance = processConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + Instance._configs.TryAdd(config.Id, config); + } + } + /// + /// 根据Id获取ProcessConfig + /// + /// + /// + /// + public ProcessConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var processConfigInfo)) + { + return processConfigInfo; + } + + throw new FileNotFoundException($"MachineConfig not find {id} Id"); + } + /// + /// 根据Id获取ProcessConfig + /// + /// + /// + /// + public bool TryGet(uint id, out ProcessConfig config) + { + return _configs.TryGetValue(id, out config); + } + /// + /// 按照startupGroup寻找属于startupGroup组的ProcessConfig + /// + /// startupGroup + /// + public IEnumerable ForEachByStartupGroup(uint startupGroup) + { + foreach (var processConfig in List) + { + if (processConfig.StartupGroup == startupGroup) + { + yield return processConfig; + } + } + } + } + /// + /// 表示一个进程配置信息 + /// + public sealed class ProcessConfig + { + /// + /// 进程Id + /// + public uint Id { get; set; } + /// + /// 机器ID + /// + public uint MachineId { get; set; } + /// + /// 启动组 + /// + public uint StartupGroup { get; set; } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta new file mode 100644 index 00000000..9e572ae6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/ProcessConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 598e92164bf3143cb9ff0ab8b641571f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/SceneConfig.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/SceneConfig.cs new file mode 100644 index 00000000..54f1efb0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/SceneConfig.cs @@ -0,0 +1,196 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.DataStructure.Collection; +using Fantasy.DataStructure.Dictionary; +using Fantasy.Helper; +using Fantasy.IdFactory; +using Newtonsoft.Json; +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8601 // Possible null reference assignment. + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net +{ + /// + /// 存放所有SceneConfigInfo信息 + /// + public sealed class SceneConfigData + { + /// + /// 存放所有SceneConfig信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + [JsonIgnore] + [IgnoreDataMember] + private readonly OneToManyList _sceneConfigBySceneType = new OneToManyList(); + [JsonIgnore] + [IgnoreDataMember] + private readonly OneToManyList _sceneConfigByProcess = new OneToManyList(); + [JsonIgnore] [IgnoreDataMember] + private readonly Dictionary>> _worldSceneTypes = new Dictionary>>(); + /// + /// 获得SceneConfigData的实例 + /// + public static SceneConfigData Instance { get; private set; } + /// + /// 初始化SceneConfig + /// + /// + public static void Initialize(string sceneConfigJson) + { + Instance = sceneConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + config.Initialize(); + Instance._configs.TryAdd(config.Id, config); + Instance._sceneConfigByProcess.Add(config.ProcessConfigId, config); + Instance._sceneConfigBySceneType.Add(config.SceneType, config); + + var configWorldConfigId = (int)config.WorldConfigId; + + if (!Instance._worldSceneTypes.TryGetValue(configWorldConfigId, out var sceneConfigDic)) + { + sceneConfigDic = new Dictionary>(); + Instance._worldSceneTypes.Add(configWorldConfigId, sceneConfigDic); + } + + if (!sceneConfigDic.TryGetValue(config.SceneType, out var sceneConfigList)) + { + sceneConfigList = new List(); + sceneConfigDic.Add(config.SceneType, sceneConfigList); + } + + sceneConfigList.Add(config); + } + } + + /// + /// 根据Id获取SceneConfig + /// + /// + /// + /// + public SceneConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var sceneConfigInfo)) + { + return sceneConfigInfo; + } + + throw new FileNotFoundException($"WorldConfig not find {id} Id"); + } + + /// + /// 根据Id获取SceneConfig + /// + /// + /// + /// + public bool TryGet(uint id, out SceneConfig config) + { + return _configs.TryGetValue(id, out config); + } + + /// + /// 获得SceneConfig + /// + /// + /// + public List GetByProcess(uint serverConfigId) + { + return _sceneConfigByProcess.TryGetValue(serverConfigId, out var list) ? list : new List(); + } + + /// + /// 获得SceneConfig + /// + /// + /// + public List GetSceneBySceneType(int sceneType) + { + return !_sceneConfigBySceneType.TryGetValue(sceneType, out var list) ? new List() : list; + } + + /// + /// 获得SceneConfig + /// + /// + /// + /// + public List GetSceneBySceneType(int world, int sceneType) + { + if (!_worldSceneTypes.TryGetValue(world, out var sceneConfigDic)) + { + return new List(); + } + + if (!sceneConfigDic.TryGetValue(sceneType, out var list)) + { + return new List(); + } + + return list; + } + } + + /// + /// 表示一个Scene配置信息 + /// + public sealed class SceneConfig + { + /// + /// ID + /// + public uint Id { get; set; } + /// + /// 进程Id + /// + public uint ProcessConfigId { get; set; } + /// + /// 世界Id + /// + public uint WorldConfigId { get; set; } + /// + /// Scene运行类型 + /// + public string SceneRuntimeType { get; set; } + /// + /// Scene类型 + /// + public string SceneTypeString { get; set; } + /// + /// 协议类型 + /// + public string NetworkProtocol { get; set; } + /// + /// 外网端口 + /// + public int OuterPort { get; set; } + /// + /// 内网端口 + /// + public int InnerPort { get; set; } + /// + /// Scene类型 + /// + public int SceneType { get; set; } + /// + /// RouteId + /// + [JsonIgnore] + [IgnoreDataMember] + public long RouteId { get; private set; } + /// + /// 初始化方法 + /// + public void Initialize() + { + RouteId = new RuntimeIdStruct(0, Id, (byte)WorldConfigId, 0); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta new file mode 100644 index 00000000..b92b264c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/SceneConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4aa38ea5c6e1e4773944e1c2f274098e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/WorldConfig.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/WorldConfig.cs new file mode 100644 index 00000000..9b0ede50 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/WorldConfig.cs @@ -0,0 +1,93 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using System.Runtime.Serialization; +using Fantasy.Helper; +using Newtonsoft.Json; +#pragma warning disable CS8601 // Possible null reference assignment. + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net +{ + /// + /// 存放所有WorldConfigInfo信息 + /// + public sealed class WorldConfigData + { + /// + /// 存放所有WorldConfigInfo信息 + /// + public List List; + [JsonIgnore] + [IgnoreDataMember] + private readonly ConcurrentDictionary _configs = new ConcurrentDictionary(); + /// + /// 获得WorldConfig的实例 + /// + public static WorldConfigData Instance { get; private set; } + /// + /// 初始化WorldConfig + /// + /// + public static void Initialize(string worldConfigJson) + { + Instance = worldConfigJson.Deserialize(); + foreach (var config in Instance.List) + { + Instance._configs.TryAdd(config.Id, config); + } + } + /// + /// 根据Id获取WorldConfig + /// + /// + /// + /// + public WorldConfig Get(uint id) + { + if (_configs.TryGetValue(id, out var worldConfigInfo)) + { + return worldConfigInfo; + } + + throw new FileNotFoundException($"WorldConfig not find {id} Id"); + } + /// + /// 根据Id获取WorldConfig + /// + /// + /// + /// + public bool TryGet(uint id, out WorldConfig config) + { + return _configs.TryGetValue(id, out config); + } + } + + /// + /// 表示一个世界配置信息 + /// + public sealed class WorldConfig + { + /// + /// Id + /// + public uint Id { get; set; } + /// + /// 名称 + /// + public string WorldName { get; set; } + /// + /// 数据库连接字符串 + /// + public string DbConnection { get; set; } + /// + /// 数据库名称 + /// + public string DbName { get; set; } + /// + /// 数据库类型 + /// + public string DbType { get; set; } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta new file mode 100644 index 00000000..e7ae1271 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ConfigTable/WorldConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 117eb806dca2a4a67bbc173d57cf98f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Entry.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Entry.cs new file mode 100644 index 00000000..7496aeee --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Entry.cs @@ -0,0 +1,122 @@ +#if FANTASY_NET +using System.Reflection; +using CommandLine; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Helper; +using Fantasy.Network; +using Fantasy.Serialize; +// ReSharper disable FunctionNeverReturns + +namespace Fantasy.Platform.Net; + +/// +/// Fantasy.Net 应用程序入口 +/// +/// 当命令行格式异常时抛出。 +/// 不支持的 ProcessType 类型异常。 +public static class Entry +{ + /// + /// 框架初始化 + /// + /// + public static void Initialize(params System.Reflection.Assembly[] assemblies) + { + // 解析命令行参数 + Parser.Default.ParseArguments(Environment.GetCommandLineArgs()) + .WithNotParsed(error => throw new Exception("Command line format error!")) + .WithParsed(option => + { + ProcessDefine.Options = option; + ProcessDefine.InnerNetwork = Enum.Parse(option.InnerNetwork); + }); + // 初始化Log系统 + Log.Initialize(); + // 检查启动参数,后期可能有机器人等不同的启动参数 + switch (ProcessDefine.Options.ProcessType) + { + case "Game": + { + break; + } + default: + { + throw new NotSupportedException($"ProcessType is {ProcessDefine.Options.ProcessType} Unrecognized!"); + } + } + + // 初始化程序集管理系统 + AssemblySystem.Initialize(assemblies); + // 初始化序列化 + SerializerManager.Initialize(); + // 精度处理(只针对Windows下有作用、其他系统没有这个问题、一般也不会用Windows来做服务器的) + WinPeriod.Initialize(); + } + + /// + /// 启动Fantasy.Net + /// + public static async FTask Start() + { + // 启动Process + StartProcess().Coroutine(); + await FTask.CompletedTask; + while (true) + { + ThreadScheduler.Update(); + Thread.Sleep(1); + } + } + + /// + /// 初始化并且启动框架 + /// + /// + public static async FTask Start(params System.Reflection.Assembly[] assemblies) + { + Initialize(assemblies); + await Start(); + } + + private static async FTask StartProcess() + { + if (ProcessDefine.Options.StartupGroup != 0) + { + foreach (var processConfig in ProcessConfigData.Instance.ForEachByStartupGroup((uint)ProcessDefine.Options.StartupGroup)) + { + await Process.Create(processConfig.Id); + } + + return; + } + + switch (ProcessDefine.Options.Mode) + { + case "Develop": + { + foreach (var processConfig in ProcessConfigData.Instance.List) + { + await Process.Create(processConfig.Id); + } + + return; + } + case "Release": + { + await Process.Create(ProcessDefine.Options.ProcessId); + return; + } + } + } + + /// + /// 关闭 Fantasy + /// + public static void Close() + { + AssemblySystem.Dispose(); + SerializerManager.Dispose(); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Entry.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Entry.cs.meta new file mode 100644 index 00000000..6006ac4c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Entry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7090806e21ca24bf0821db96a4e47b9f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Process.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Process.cs new file mode 100644 index 00000000..63ec20aa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Process.cs @@ -0,0 +1,150 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +using Fantasy.Async; +using Fantasy.IdFactory; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8601 // Possible null reference assignment. +namespace Fantasy.Platform.Net; + +/// +/// 一个进程的实例 +/// +public sealed class Process : IDisposable +{ + /// + /// 当前进程的Id + /// + public readonly uint Id; + /// + /// 进程关联的MachineId + /// + public readonly uint MachineId; + private readonly ConcurrentDictionary _processScenes = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary Scenes = new ConcurrentDictionary(); + private Process() {} + private Process(uint id, uint machineId) + { + Id = id; + MachineId = machineId; + } + + internal bool IsProcess(ref long routeId) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + return _processScenes.ContainsKey(sceneId); + } + + internal bool IsProcess(ref uint sceneId) + { + return _processScenes.ContainsKey(sceneId); + } + + internal void AddSceneToProcess(Scene scene) + { + _processScenes.TryAdd(scene.SceneConfigId, scene); + } + + internal void RemoveSceneToProcess(Scene scene, bool isDispose) + { + _processScenes.Remove(scene.SceneConfigId, out _); + + if (isDispose) + { + scene.Dispose(); + } + } + + internal bool TryGetSceneToProcess(long routeId, out Scene scene) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + return _processScenes.TryGetValue(sceneId, out scene); + } + + internal bool TryGetSceneToProcess(uint sceneId, out Scene scene) + { + return _processScenes.TryGetValue(sceneId, out scene); + } + /// + /// 销毁方法 + /// + public void Dispose() + { + if (_processScenes.IsEmpty) + { + return; + } + + var sceneQueue = new Queue(); + + foreach (var (_, scene) in _processScenes) + { + sceneQueue.Enqueue(scene); + } + + while (sceneQueue.TryDequeue(out var removeScene)) + { + removeScene.Dispose(); + } + + _processScenes.Clear(); + } + + internal static async FTask Create(uint processConfigId) + { + if (!ProcessConfigData.Instance.TryGet(processConfigId, out var processConfig)) + { + Log.Error($"not found processConfig by Id:{processConfigId}"); + return null; + } + + if (!MachineConfigData.Instance.TryGet(processConfig.MachineId, out var machineConfig)) + { + Log.Error($"not found machineConfig by Id:{processConfig.MachineId}"); + return null; + } + + var process = new Process(processConfigId, processConfig.MachineId); + var sceneConfigs = SceneConfigData.Instance.GetByProcess(processConfigId); + + foreach (var sceneConfig in sceneConfigs) + { + await Scene.Create(process, machineConfig, sceneConfig); + } + + Log.Info($"Process:{processConfigId} Startup Complete SceneCount:{sceneConfigs.Count}"); + return process; + } + + internal bool IsInAppliaction(ref uint sceneId) + { + return _processScenes.ContainsKey(sceneId); + } + + internal static void AddScene(Scene scene) + { + Scenes.TryAdd(scene.SceneConfigId, scene); + } + + internal static void RemoveScene(Scene scene, bool isDispose) + { + Scenes.Remove(scene.SceneConfigId, out _); + + if (isDispose) + { + scene.Dispose(); + } + } + + internal static bool TryGetScene(long routeId, out Scene scene) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref routeId); + return Scenes.TryGetValue(sceneId, out scene); + } + + internal static bool TryGetScene(uint sceneId, out Scene scene) + { + return Scenes.TryGetValue(sceneId, out scene); + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Process.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Process.cs.meta new file mode 100644 index 00000000..34b89136 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/Process.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0670c483737fa4507b7c48e609e91ed0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ProcessDefine.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ProcessDefine.cs new file mode 100644 index 00000000..2bcc4e09 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ProcessDefine.cs @@ -0,0 +1,99 @@ +#if FANTASY_NET +using CommandLine; +using Fantasy.Network; + +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy.Platform.Net; + +/// +/// Process运行模式 +/// +public enum ProcessMode +{ + /// + /// 默认 + /// + None =0, + /// + /// 开发模式 + /// + Develop = 1, + /// + /// 发布模式 + /// + Release = 2 +} + +internal sealed class CommandLineOptions +{ + /// + /// 用于启动指定的进程,该进程的 ID 与 ProcessConfig 的 ID 相关联。此参数只能传递单个 ID,不支持传递多个 ID。 + /// + [Option("pid", Required = false, Default = (uint)0, HelpText = "Enter an ProcessIdId such as 1")] + public uint ProcessId { get; set; } + /// + /// Process类型,获取或设置应用程序的类型。 + /// Game - 游戏服务器Process + /// Robot - 机器人(暂未支持该功能) + /// + [Option('a', "ProcessType", Required = false, Default = "Game", HelpText = "Game")] + public string ProcessType { get; set; } + /// + /// 服务器运行模式,获取或设置服务器的运行模式。 + /// Develop - 开发模式(启动Process配置表中的所有Process) + /// Release - 发布模式(根据ProcessId启动Process) + /// + [Option('m', "Mode", Required = true, Default = "Release", HelpText = "Develop:启动Process配置表中的所有Process,\nRelease:根据ProcessId启动Process")] + public string Mode { get; set; } + /// + /// 服务器内部网络协议 + /// TCP - 服务器内部之间通讯使用TCP协议 + /// KCP - 服务器内部之间通讯使用KCP协议 + /// WebSocket - 服务器内部之间通讯使用WebSocket协议(不推荐、TCP或KCP) + /// + [Option('n', "InnerNetwork", Required = false, Default = "TCP", HelpText = "TCP、KCP、WebSocket")] + public string InnerNetwork { get; set; } + /// + /// 会话空闲检查超时时间。 + /// + [Option('t', "SessionIdleCheckerTimeout", Required = false, Default = 8000, HelpText = "Session idle check timeout")] + public int SessionIdleCheckerTimeout { get; set; } + /// + /// 会话空闲检查间隔。 + /// + [Option('i', "SessionIdleCheckerInterval", Required = false, Default = 5000, HelpText = "Session idle check interval")] + public int SessionIdleCheckerInterval { get; set; } + /// + /// 启动组。 + /// + [Option('g', "StartupGroup", Required = false, Default = 0, HelpText = "Used to start a group of Process")] + public int StartupGroup { get; set; } +} + +/// +/// AppDefine +/// +internal static class ProcessDefine +{ + /// + /// 命令行选项 + /// + public static CommandLineOptions Options; + /// + /// App程序Id + /// + public static uint ProcessId => Options.ProcessId; + /// + /// 会话空闲检查超时时间。 + /// + public static int SessionIdleCheckerTimeout => Options.SessionIdleCheckerTimeout; + /// + /// 会话空闲检查间隔。 + /// + public static int SessionIdleCheckerInterval => Options.SessionIdleCheckerInterval; + /// + /// 内部网络通讯协议类型 + /// + public static NetworkProtocolType InnerNetwork; +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ProcessDefine.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ProcessDefine.cs.meta new file mode 100644 index 00000000..519edca8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ProcessDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4277db03538f5471dacacbe0e8e24343 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ThreadSynchronizationContext.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ThreadSynchronizationContext.cs new file mode 100644 index 00000000..bb2948af --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ThreadSynchronizationContext.cs @@ -0,0 +1,52 @@ +#if FANTASY_NET +using System.Collections.Concurrent; +#pragma warning disable CS8765 +#pragma warning disable CS8601 +#pragma warning disable CS8618 + +namespace Fantasy; + +/// +/// 线程的同步上下文 +/// +public sealed class ThreadSynchronizationContext : SynchronizationContext +{ + private readonly ConcurrentQueue _queue = new(); + /// + /// 执行当前上下文投递过的逻辑 + /// + public void Update() + { + while (_queue.TryDequeue(out var actionHandler)) + { + try + { + actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + /// + /// 投递一个逻辑到当前上下文 + /// + /// + /// + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + /// + /// 投递一个逻辑到当前上下文 + /// + /// + public void Post(Action action) + { + _queue.Enqueue(action); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta new file mode 100644 index 00000000..7daf0126 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Net/ThreadSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cea36857aef5447079bd1baa46ab8e69 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity.meta new file mode 100644 index 00000000..ae0c20d2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8b2867f300822489981d595e5b3ca9fc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/AppDefine.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/AppDefine.cs new file mode 100644 index 00000000..d9d85aef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/AppDefine.cs @@ -0,0 +1,19 @@ +#if FANTASY_UNITY +namespace Fantasy.Platform.Unity +{ + public static class AppDefine + { + public static string RemoteUpdatePath; + public static bool EditorModel = true; + public const string VersionName = "version.bytes"; + public const string VersionMD5Name = "version.md5"; + public const string AssetBundleManifestName = "Fantasy"; + public static bool IsEditor => UnityEngine.Application.isEditor && EditorModel; + public static string AssetBundleSaveDirectory => "Assets/AssetBundles"; + public static string LocalAssetBundlePath => UnityEngine.Application.streamingAssetsPath; + public static string RemoteAssetBundlePath => UnityEngine.Application.persistentDataPath; + public static string PersistentDataVersion => $"{UnityEngine.Application.persistentDataPath}/{VersionName}"; + public static string StreamingAssetsVersion => $"{UnityEngine.Application.streamingAssetsPath}/{VersionName}"; + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/AppDefine.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/AppDefine.cs.meta new file mode 100644 index 00000000..5a0ff14a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/AppDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83a8f65932d754f82818737683b6066b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes.meta new file mode 100644 index 00000000..17b4bbdb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 59760e44e339e470d848463650cd929c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs new file mode 100644 index 00000000..49914ec7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonDefaultValueAttribute : Attribute + { + public BsonDefaultValueAttribute(object defaultValue) { } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta new file mode 100644 index 00000000..2d6be4db --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonDefaultValueAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0667920f73ddb4da4b61aaf8a6704520 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs new file mode 100644 index 00000000..38927278 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs @@ -0,0 +1,13 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonElementAttribute : Attribute + { + public BsonElementAttribute() { } + + public BsonElementAttribute(string elementName) { } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta new file mode 100644 index 00000000..4de7566a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonElementAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1bd8935bc9b394975ba1c0eeab13f817 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs new file mode 100644 index 00000000..48274d08 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class BsonIdAttribute : Attribute + { + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta new file mode 100644 index 00000000..b014fb9a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIdAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a024b9c70f7be4dfd8d94e184d729f63 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs new file mode 100644 index 00000000..23e55c81 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonIgnoreAttribute : Attribute + { + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta new file mode 100644 index 00000000..e2cc58c3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e44cd65ae1ffc4545a329acf15eaf24b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs new file mode 100644 index 00000000..82dddde6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs @@ -0,0 +1,13 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class BsonIgnoreIfDefaultAttribute : Attribute + { + public BsonIgnoreIfDefaultAttribute() { } + + public BsonIgnoreIfDefaultAttribute(bool value) { } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta new file mode 100644 index 00000000..e8488ad0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfDefaultAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28808e0d128ab46e2b98ad3285c6fd3d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs new file mode 100644 index 00000000..f330a8b9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs @@ -0,0 +1,11 @@ +#if FANTASY_UNITY +using System; +namespace MongoDB.Bson.Serialization.Attributes +{ + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class BsonIgnoreIfNullAttribute : Attribute + { + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta new file mode 100644 index 00000000..e70b6ba5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Attributes/BsonIgnoreIfNullAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6e7c0b5e3e9c4119aa3eddbe2bad2e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Entry.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Entry.cs new file mode 100644 index 00000000..72ae6294 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Entry.cs @@ -0,0 +1,102 @@ +#if FANTASY_UNITY +using System.Reflection; +using Cysharp.Threading.Tasks; +using Fantasy.Assembly; +using Fantasy.Async; +using Fantasy.Serialize; +using UnityEngine; +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Platform.Unity +{ + public sealed class FantasyObject : MonoBehaviour + { + public static GameObject FantasyObjectGameObject { get; private set; } + // 这个方法将在游戏启动时自动调用 + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void OnRuntimeMethodLoad() + { + FantasyObjectGameObject = new GameObject("Fantasy.Net"); + DontDestroyOnLoad(FantasyObjectGameObject); + } + private void OnApplicationQuit() + { + Destroy(FantasyObjectGameObject); + } + } + + public struct OnSceneCreate + { + public Scene Scene; + public object Arg; + } + + public class Entry : MonoBehaviour + { + private static bool _isInit; + public static Scene Scene { get; private set; } + + /// + /// 初始化框架 + /// + /// + public static void Initialize(params System.Reflection.Assembly[] assemblies) + { + if (_isInit) + { + Log.Error("Fantasy has already been initialized and does not need to be initialized again!"); + return; + } + Log.Register(new UnityLog()); + // 初始化程序集管理系统 + AssemblySystem.Initialize(assemblies); + // 初始化序列化 + SerializerManager.Initialize(); +#if FANTASY_WEBGL + ThreadSynchronizationContext.Initialize(); +#endif + _isInit = true; + FantasyObject.FantasyObjectGameObject.AddComponent(); + Log.Debug("Fantasy Initialize Complete!"); + } + + /// + /// 在Entry中创建一个Scene,如果Scene已经被创建过,将先销毁Scene再创建。 + /// + /// + /// + /// + public static async UniTask CreateScene(object arg = null, string sceneRuntimeType = SceneRuntimeType.MainThread) + { + Scene?.Dispose(); + Scene = await Scene.Create(sceneRuntimeType); + await Scene.EventComponent.PublishAsync(new OnSceneCreate() + { + Arg = arg, + Scene = Scene + }); + return Scene; + } + + private void Update() + { + ThreadScheduler.Update(); + } + + private void OnDestroy() + { + AssemblySystem.Dispose(); + SerializerManager.Dispose(); + if (Scene != null) + { + Scene?.Dispose(); + Scene = null; + } + _isInit = false; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Entry.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Entry.cs.meta new file mode 100644 index 00000000..e6847bcc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Entry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5933a48a517474c518cd76d492bb0660 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Temp.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Temp.cs new file mode 100644 index 00000000..399488fd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Temp.cs @@ -0,0 +1,108 @@ +// using System.Reflection; +// using Fantasy.Assembly; +// using Fantasy.Async; +// // using UnityEngine; +// #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value +// #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +// #pragma warning disable CS8603 // Possible null reference return. +// #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +// #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +// +// namespace Fantasy.Platform.Unity +// { +// public class MonoBehaviour +// { +// +// } +// +// public class GameObject +// { +// public GameObject(string name) +// { +// +// } +// } +// +// internal enum RuntimeInitializeLoadType +// { +// BeforeSceneLoad = 1, +// } +// +// internal class RuntimeInitializeOnLoadMethodAttribute : Attribute +// { +// public RuntimeInitializeLoadType RuntimeInitializeLoadType; +// +// public RuntimeInitializeOnLoadMethodAttribute(RuntimeInitializeLoadType loadType) +// { +// +// } +// } +// +// public sealed class FantasyObject : MonoBehaviour +// { +// public static GameObject FantasyObjectGameObject { get; private set; } +// // 这个方法将在游戏启动时自动调用 +// [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] +// static void OnRuntimeMethodLoad() +// { +// FantasyObjectGameObject = new GameObject("Fantasy.Net"); +// // DontDestroyOnLoad(FantasyObjectGameObject); +// } +// private void OnApplicationQuit() +// { +// // Destroy(FantasyObjectGameObject); +// } +// } +// +// public struct OnFantasyInit +// { +// public Scene Scene; +// } +// +// public class Entry : MonoBehaviour +// { +// private static bool _isInit; +// public static Scene Scene { get; private set; } +// /// +// /// 初始化框架 +// /// +// public static async FTask Initialize(params System.Reflection.Assembly[] assemblies) +// { +// Scene?.Dispose(); +// // 初始化程序集管理系统 +// AssemblySystem.Initialize(assemblies); +// if (!_isInit) +// { +// #if FANTASY_WEBGL +// ThreadSynchronizationContext.Initialize(); +// #endif +// _isInit = true; +// // FantasyObject.FantasyObjectGameObject.AddComponent(); +// } +// // Scene = await Scene.Create(SceneRuntimeType.MainThread); +// // await Scene.EventComponent.PublishAsync(new OnFantasyInit() +// // { +// // Scene = Scene +// // }); +// // return Scene; +// await FTask.CompletedTask; +// return null; +// } +// +// private void Update() +// { +// ThreadScheduler.Update(); +// } +// +// private void OnDestroy() +// { +// AssemblySystem.Dispose(); +// if (Scene != null) +// { +// Scene?.Dispose(); +// Scene = null; +// } +// _isInit = false; +// } +// } +// } diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Temp.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Temp.cs.meta new file mode 100644 index 00000000..16ecc76e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/Temp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 907556dab37dc4fff866197541010500 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/ThreadSynchronizationContext.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/ThreadSynchronizationContext.cs new file mode 100644 index 00000000..44b165a1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/ThreadSynchronizationContext.cs @@ -0,0 +1,104 @@ +#if FANTASY_UNITY && !FANTASY_WEBGL +#pragma warning disable CS8765 +#pragma warning disable CS8601 +#pragma warning disable CS8618 +using System; +using System.Collections.Concurrent; +using System.Threading; + +namespace Fantasy +{ + public sealed class ThreadSynchronizationContext : SynchronizationContext + { + private Action _actionHandler; + private readonly ConcurrentQueue _queue = new(); + + public void Update() + { + while (_queue.TryDequeue(out _actionHandler)) + { + try + { + _actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + public void Post(Action action) + { + _queue.Enqueue(action); + } + } +} +#endif +#if FANTASY_UNITY && FANTASY_WEBGL +using System; +using System.Collections.Generic; +using System.Threading; +using Fantasy; +using UnityEngine; +using Object = UnityEngine.Object; + +public class WebGLSynchronizationContextUpdater : MonoBehaviour +{ + private ThreadSynchronizationContext _context; + + public void Initialize(ThreadSynchronizationContext context) + { + _context = context; + } + + void Update() + { + _context.Update(); + } +} +public sealed class ThreadSynchronizationContext : SynchronizationContext +{ + private Action _actionHandler; + private readonly Queue _queue = new(); + + public static void Initialize() + { + var context = new ThreadSynchronizationContext(); + SetSynchronizationContext(context); + var go = new GameObject("WebGLSynchronizationContextUpdater"); + go.AddComponent().Initialize(context); + Object.DontDestroyOnLoad(go); + } + + public void Update() + { + while (_queue.TryDequeue(out _actionHandler)) + { + try + { + _actionHandler(); + } + catch (Exception e) + { + Log.Error(e); + } + } + } + + public override void Post(SendOrPostCallback callback, object state) + { + Post(() => callback(state)); + } + + public void Post(Action action) + { + _queue.Enqueue(action); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta new file mode 100644 index 00000000..342fd876 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Platform/Unity/ThreadSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e96cc25874c304ccd829d3e15f992501 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool.meta new file mode 100644 index 00000000..7dcce413 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 46bce4db32ba4430abfb962eb6636d2e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent.meta new file mode 100644 index 00000000..ff1cc589 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 40200134f8074457ab6709111b2d3046 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPool.cs new file mode 100644 index 00000000..4c946d1a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPool.cs @@ -0,0 +1,37 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Pool +{ + /// + /// 线程安全的静态通用对象池。 + /// + internal static class MultiThreadPool + { + private static readonly ConcurrentDictionary ObjectPools = new ConcurrentDictionary(); + + public static T Rent() where T : IPool, new() + { + return ObjectPools.GetOrAdd(typeof(T), t => new MultiThreadPoolQueue(2000, () => new T())).Rent(); + } + + public static IPool Rent(Type type) + { + return ObjectPools.GetOrAdd(type, t => new MultiThreadPoolQueue(2000, CreateInstance.CreateIPool(type))).Rent(); + } + + public static void Return(T obj) where T : IPool, new() + { + if (!obj.IsPool()) + { + return; + } + + ObjectPools.GetOrAdd(typeof(T), t => new MultiThreadPoolQueue(2000, () => new T())).Return(obj); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPool.cs.meta new file mode 100644 index 00000000..e0ae74ae --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f4295246cc4ad4e9ab1c09acbc4bbbc1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs new file mode 100644 index 00000000..df15a1c9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs @@ -0,0 +1,76 @@ +#if !FANTASY_WEBGL +using System; +using System.Collections.Concurrent; +using System.Threading; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Pool +{ + /// + /// 线程安全的对象池。 + /// + internal class MultiThreadPoolQueue + { + private int _poolCount; + private readonly int _maxCapacity; + private readonly Func _createInstance; + private readonly ConcurrentQueue _poolQueue = new ConcurrentQueue(); + private MultiThreadPoolQueue() { } + + public MultiThreadPoolQueue(int maxCapacity, Func createInstance) + { + _maxCapacity = maxCapacity; + _createInstance = createInstance; + } + + public T Rent() where T : IPool, new() + { + if (!_poolQueue.TryDequeue(out var t)) + { + var pool = new T(); + pool.SetIsPool(true); + return pool; + } + + t.SetIsPool(true); + Interlocked.Decrement(ref _poolCount); + return (T)t; + } + + public IPool Rent() + { + if (!_poolQueue.TryDequeue(out var t)) + { + var instance = _createInstance(); + instance.SetIsPool(true); + return instance; + } + + t.SetIsPool(true); + Interlocked.Decrement(ref _poolCount); + return t; + } + + public void Return(IPool obj) + { + if (!obj.IsPool()) + { + return; + } + + obj.SetIsPool(false); + + if (Interlocked.Increment(ref _poolCount) <= _maxCapacity) + { + _poolQueue.Enqueue(obj); + return; + } + + Interlocked.Decrement(ref _poolCount); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta new file mode 100644 index 00000000..d9a32671 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Concurrent/MultiThreadPoolQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5520348a236554f5380103f259f87dfd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface.meta new file mode 100644 index 00000000..07e6c923 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e11c514da50264cc986ac5c6a85ea450 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface/IPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface/IPool.cs new file mode 100644 index 00000000..1775f28b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface/IPool.cs @@ -0,0 +1,18 @@ +namespace Fantasy.Pool +{ + /// + /// 实现了这个接口代表支持对象池 + /// + public interface IPool + { + /// + /// 是否从池里创建的 + /// + bool IsPool(); + /// + /// 设置是否从池里创建的 + /// + /// + void SetIsPool(bool isPool); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface/IPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface/IPool.cs.meta new file mode 100644 index 00000000..44c50ffa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Interface/IPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 91cd6661b42dc41cfaad00203a86ce3c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal.meta new file mode 100644 index 00000000..08b4f536 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 554c5e3bc9c1844f99046f84eb4c2de2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/Pool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/Pool.cs new file mode 100644 index 00000000..88006e18 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/Pool.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +// ReSharper disable CheckNamespace + +namespace Fantasy.Pool +{ + /// + /// 静态的对象池系统,不支持多线程。 + /// + /// + public static class Pool where T : IPool, new() + { + private static readonly Queue PoolQueue = new Queue(); + /// + /// 池子里可用的数量 + /// + public static int Count => PoolQueue.Count; + + /// + /// 租借 + /// + /// + public static T Rent() + { + return PoolQueue.Count == 0 ? new T() : PoolQueue.Dequeue(); + } + + /// + /// 租借 + /// + /// 如果池子里没有,会先执行这个委托。 + /// + public static T Rent(Func generator) + { + return PoolQueue.Count == 0 ? generator() : PoolQueue.Dequeue(); + } + + /// + /// 返还 + /// + /// + public static void Return(T t) + { + if (t == null) + { + return; + } + + PoolQueue.Enqueue(t); + } + + /// + /// 返还 + /// + /// 返还的东西 + /// 返还后执行的委托 + public static void Return(T t, Action reset) + { + if (t == null) + { + return; + } + + reset(t); + PoolQueue.Enqueue(t); + } + + /// + /// 清空池子 + /// + public static void Clear() + { + PoolQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/Pool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/Pool.cs.meta new file mode 100644 index 00000000..ef447aae --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/Pool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6bf3e1dd4e39a4ae4ababd3770ed431d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolCore.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolCore.cs new file mode 100644 index 00000000..f51de87d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolCore.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Fantasy.DataStructure.Collection; + +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8603 // Possible null reference return. + +namespace Fantasy.Pool +{ + /// + /// 对象池抽象接口,用于创建和管理可重复使用的对象实例。 + /// + public abstract class PoolCore : IDisposable + { + private int _poolCount; + private readonly int _maxCapacity; + /// + /// 池子里可用的数量 + /// + public int Count => _poolQueue.Count; + private readonly OneToManyQueue _poolQueue = new OneToManyQueue(); + private readonly Dictionary> _typeCheckCache = new Dictionary>(); + + /// + /// 构造函数 + /// + /// 初始的容量 + protected PoolCore(int maxCapacity) + { + _maxCapacity = maxCapacity; + } + + /// + /// 租借 + /// + /// + /// + public T Rent() where T : IPool, new() + { + if (!_poolQueue.TryDequeue(typeof(T), out var queue)) + { + return new T(); + } + + queue.SetIsPool(true); + _poolCount--; + return (T)queue; + } + + /// + /// 租借 + /// + /// 租借的类型 + /// + /// + public IPool Rent(Type type) + { + if (!_poolQueue.TryDequeue(type, out var queue)) + { + if (!_typeCheckCache.TryGetValue(type, out var createInstance)) + { + if (!typeof(IPool).IsAssignableFrom(type)) + { + throw new NotSupportedException($"{this.GetType().FullName} Type:{type.FullName} must inherit from IPool"); + } + else + { + createInstance = CreateInstance.CreateIPool(type); + _typeCheckCache[type] = createInstance; + } + } + + var instance = createInstance(); + instance.SetIsPool(true); + return instance; + } + + queue.SetIsPool(true); + _poolCount--; + return queue; + } + + /// + /// 返还 + /// + /// + /// + public void Return(Type type, IPool obj) + { + if (obj == null) + { + return; + } + + if (!obj.IsPool()) + { + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + _poolCount++; + obj.SetIsPool(false); + _poolQueue.Enqueue(type, obj); + } + + /// + /// 销毁方法 + /// + public virtual void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + _typeCheckCache.Clear(); + } + } + + /// + /// 泛型对象池核心类,用于创建和管理可重复使用的对象实例。 + /// + /// 要池化的对象类型 + public abstract class PoolCore where T : IPool, new() + { + private int _poolCount; + private readonly int _maxCapacity; + private readonly Queue _poolQueue = new Queue(); + /// + /// 池子里可用的数量 + /// + public int Count => _poolQueue.Count; + + /// + /// 构造函数 + /// + /// 初始的容量 + protected PoolCore(int maxCapacity) + { + _maxCapacity = maxCapacity; + } + + /// + /// 租借 + /// + /// + public virtual T Rent() + { + if (_poolQueue.Count == 0) + { + return new T(); + } + + var dequeue = _poolQueue.Dequeue(); + dequeue.SetIsPool(true); + _poolCount--; + return dequeue; + } + + /// + /// 返还 + /// + /// + public virtual void Return(T item) + { + if (item == null) + { + return; + } + + if (!item.IsPool()) + { + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + _poolCount++; + item.SetIsPool(false); + _poolQueue.Enqueue(item); + } + + /// + /// 销毁方法 + /// + public virtual void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolCore.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolCore.cs.meta new file mode 100644 index 00000000..5ed7e6a1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolCore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 12336238185b447c1af2fbd1eb1f2b7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolWithDisposable.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolWithDisposable.cs new file mode 100644 index 00000000..f206bec4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolWithDisposable.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + +namespace Fantasy.Pool +{ + /// + /// 静态通用对象池,用于存储实现了 IDisposable 接口的对象。 + /// + /// 要存储在对象池中的对象类型,必须实现 IDisposable 接口。 + public abstract class PoolWithDisposable : IDisposable where T : IPool, IDisposable, new() + { + private int _poolCount; + private readonly int _maxCapacity; + private readonly Queue _poolQueue = new Queue(); + /// + /// 池子里可用的数量 + /// + public int Count => _poolQueue.Count; + + /// + /// 构造函数 + /// + /// 初始的容量 + protected PoolWithDisposable(int maxCapacity) + { + _maxCapacity = maxCapacity; + } + + /// + /// 租借 + /// + /// + public T Rent() + { + if (_poolQueue.Count == 0) + { + return new T(); + } + + var dequeue = _poolQueue.Dequeue(); + dequeue.SetIsPool(true); + _poolCount--; + return dequeue; + } + + /// + /// 租借 + /// + /// + /// + public T Rent(Func generator) + { + if (_poolQueue.Count == 0) + { + return generator(); + } + + var dequeue = _poolQueue.Dequeue(); + dequeue.SetIsPool(true); + _poolCount--; + return dequeue; + } + + /// + /// 返还 + /// + /// + public void Return(T t) + { + if (t == null) + { + return; + } + + if (!t.IsPool()) + { + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + _poolCount++; + t.SetIsPool(true); + _poolQueue.Enqueue(t); + t.Dispose(); + } + + /// + /// 返还 + /// + /// + /// + public void Return(T t, Action reset) + { + if (t == null) + { + return; + } + + if (!t.IsPool()) + { + reset(t); + return; + } + + if (_poolCount >= _maxCapacity) + { + return; + } + + reset(t); + _poolCount++; + t.SetIsPool(false); + _poolQueue.Enqueue(t); + t.Dispose(); + } + + /// + /// 销毁方法 + /// + public virtual void Dispose() + { + _poolCount = 0; + _poolQueue.Clear(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolWithDisposable.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolWithDisposable.cs.meta new file mode 100644 index 00000000..9fa44762 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/Normal/PoolWithDisposable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 37d96a9ea60d8412c9c549446e970aaf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/PoolHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/PoolHelper.cs new file mode 100644 index 00000000..d9214fd3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/PoolHelper.cs @@ -0,0 +1,79 @@ +using System; +using System.Reflection.Emit; +using Fantasy.Serialize; + +#pragma warning disable CS8604 // Possible null reference argument. + +namespace Fantasy.Pool +{ + internal static class CreateInstance where T : IPool + { + public static Func Create { get; } + + static CreateInstance() + { + var type = typeof(T); + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + Create = (Func) dynamicMethod.CreateDelegate(typeof(Func)); + } + } + + internal static class CreateInstance + { + public static Func CreateIPool(Type type) + { + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + public static Func CreateObject(Type type) + { + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + public static Func CreateMessage(Type type) + { + var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + var il = dynamicMethod.GetILGenerator(); + il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + il.Emit(OpCodes.Ret); + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + } + + // public static class CreateInstance + // { + // public static Func Create(Type type) + // { + // var dynamicMethod = new DynamicMethod($"CreateInstance_{type.Name}", type, Type.EmptyTypes, true); + // var il = dynamicMethod.GetILGenerator(); + // il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes)); + // il.Emit(OpCodes.Ret); + // return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + // } + // } + + // /// + // /// 利用泛型的特性来减少反射的使用。 + // /// + // /// + // public static class PoolChecker where T : new() + // { + // public static bool IsPool { get; } + // + // static PoolChecker() + // { + // IsPool = typeof(IPool).IsAssignableFrom(typeof(T)); + // } + // } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/PoolHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/PoolHelper.cs.meta new file mode 100644 index 00000000..d7a30a70 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Pool/PoolHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4ad79f875091b4737a22bfd0e0e686ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene.meta new file mode 100644 index 00000000..2c4f375a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d7ee3aae904e54dbfb290c22a09ff730 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/ISceneUpdate.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/ISceneUpdate.cs new file mode 100644 index 00000000..f736edfb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/ISceneUpdate.cs @@ -0,0 +1,15 @@ +namespace Fantasy +{ + internal interface ISceneUpdate + { + void Update(); + } + + internal sealed class EmptySceneUpdate : ISceneUpdate + { + public void Update() + { + + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/ISceneUpdate.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/ISceneUpdate.cs.meta new file mode 100644 index 00000000..e84c60f1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/ISceneUpdate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 459c867d43e7443cd8e9b181b1f61b8c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/OnCreateSceneEvent.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/OnCreateSceneEvent.cs new file mode 100644 index 00000000..d192300f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/OnCreateSceneEvent.cs @@ -0,0 +1,22 @@ +namespace Fantasy +{ + /// + /// 当Scene创建完成后发送的事件参数 + /// + public struct OnCreateScene + { + /// + /// 获取与事件关联的场景实体。 + /// + public readonly Scene Scene; + /// + /// 初始化一个新的 OnCreateScene 实例。 + /// + /// + public OnCreateScene(Scene scene) + { + Scene = scene; + } + } + +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/OnCreateSceneEvent.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/OnCreateSceneEvent.cs.meta new file mode 100644 index 00000000..108e36ac --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/OnCreateSceneEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b47d13e99ac5412e88fb1b68d1da7b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scene.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scene.cs new file mode 100644 index 00000000..181ca8bc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scene.cs @@ -0,0 +1,534 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Cysharp.Threading.Tasks; +using Fantasy.Async; +using Fantasy.Entitas; +using Fantasy.Event; +using Fantasy.IdFactory; +using Fantasy.Network; +using Fantasy.Network.Interface; +using Fantasy.Pool; +using Fantasy.Scheduler; +using Fantasy.Timer; +#if FANTASY_NET +using Fantasy.DataBase; +using Fantasy.Platform.Net; +using Fantasy.SingleCollection; +using System.Runtime.CompilerServices; +using Fantasy.Network.Route; +#endif +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +namespace Fantasy +{ + /// + /// 表示一个场景实体,用于创建与管理特定的游戏场景信息。 + /// + public partial class Scene : Entity + { + #region Members +#if FANTASY_NET + /// + /// Scene类型,对应SceneConfig的SceneType + /// + public int SceneType { get; private set; } + /// + /// 所属的世界 + /// + public World World { get; private set; } + /// + /// 所在的Process + /// + public Process Process { get; private set; } + /// + /// SceneConfig的Id + /// + public uint SceneConfigId { get; private set; } + internal ANetwork InnerNetwork { get; private set; } + internal ANetwork OuterNetwork { get; private set; } + internal SceneConfig SceneConfig => SceneConfigData.Instance.Get(SceneConfigId); + private readonly Dictionary _processSessionInfos = new Dictionary(); +#endif + /// + /// 当前Scene的上下文 + /// + public ThreadSynchronizationContext ThreadSynchronizationContext { get; internal set; } + /// + /// 当前Scene的下创建的Entity + /// + internal readonly Dictionary Entities = new Dictionary(); + internal readonly Dictionary> TypeInstance = new Dictionary>(); + #endregion + + #region IdFactory + + /// + /// Entity实体Id的生成器 + /// + public EntityIdFactory EntityIdFactory { get; private set; } + /// + /// Entity实体RuntimeId的生成器 + /// + public RuntimeIdFactory RuntimeIdFactory { get; private set; } + + #endregion + + #region Pool + + internal EntityPool EntityPool; + internal EntityListPool EntityListPool; + internal EntitySortedDictionaryPool EntitySortedDictionaryPool; + + #endregion + + #region Component + + /// + /// Scene下的任务调度器系统组件 + /// + public TimerComponent TimerComponent { get; internal set; } + /// + /// Scene下的事件系统组件 + /// + public EventComponent EventComponent { get; internal set; } + /// + /// Scene下的ESC系统组件 + /// + public EntityComponent EntityComponent { get; internal set; } + /// + /// Scene下的网络消息对象池组件 + /// + public MessagePoolComponent MessagePoolComponent { get; internal set; } + /// + /// Scene下的协程锁组件 + /// + public CoroutineLockComponent CoroutineLockComponent { get; internal set; } + /// + /// Scene下的网络消息派发组件 + /// + internal MessageDispatcherComponent MessageDispatcherComponent { get; set; } + /// + /// Scene下的内网消息发送组件 + /// + public NetworkMessagingComponent NetworkMessagingComponent { get; internal set; } +#if FANTASY_NET + /// + /// Scene下的Entity分表组件 + /// + public SingleCollectionComponent SingleCollectionComponent { get; internal set; } +#endif + #endregion + + #region Initialize + + private async UniTask Initialize() + { + EntityPool = new EntityPool(); + EntityListPool = new EntityListPool(); + EntitySortedDictionaryPool = new EntitySortedDictionaryPool(); + SceneUpdate = EntityComponent = await Create(this, false, false).Initialize(); + MessagePoolComponent = AddComponent(false); + EventComponent = await AddComponent(false).Initialize(); + TimerComponent = AddComponent(false).Initialize(); + CoroutineLockComponent = AddComponent(false).Initialize(); + MessageDispatcherComponent = await AddComponent(false).Initialize(); + NetworkMessagingComponent = AddComponent(false); +#if FANTASY_NET + SingleCollectionComponent = await AddComponent(false).Initialize(); +#endif + } + + private void InitializeSubScene(Scene scene) + { + EntityPool = scene.EntityPool; + EntityListPool = scene.EntityListPool; + EntitySortedDictionaryPool = scene.EntitySortedDictionaryPool; + SceneUpdate = scene.SceneUpdate; + TimerComponent = scene.TimerComponent; + EventComponent = scene.EventComponent; + EntityComponent = scene.EntityComponent; + MessagePoolComponent = scene.MessagePoolComponent; + CoroutineLockComponent = scene.CoroutineLockComponent; + MessageDispatcherComponent = scene.MessageDispatcherComponent; + NetworkMessagingComponent = scene.NetworkMessagingComponent; +#if FANTASY_NET + SingleCollectionComponent = scene.SingleCollectionComponent; +#endif + } + /// + /// Scene销毁方法,执行了该方法会把当前Scene下的所有实体都销毁掉。 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } +#if FANTASY_NET + foreach (var (_, innerSession) in _processSessionInfos) + { + innerSession.Dispose(); + } + _processSessionInfos.Clear(); +#endif +#if FANTASY_UNITY + Session = null; + _unityWorldId--; + _unitySceneId--; + UnityNetwork?.Dispose(); +#endif + TypeInstance.Clear(); + EventComponent.Dispose(); + MessagePoolComponent.Dispose(); + EntityPool.Dispose(); + EntityListPool.Dispose(); + EntitySortedDictionaryPool.Dispose(); + base.Dispose(); + } + + #endregion + + internal ISceneUpdate SceneUpdate { get; set; } + + internal void Update() + { + try + { + SceneUpdate.Update(); + } + catch (Exception e) + { + Log.Error(e); + } + } + + #region Create + +#if FANTASY_UNITY || FANTASY_CONSOLE + private static uint _unitySceneId = 0; + private static byte _unityWorldId = 0; + public Session Session { get; private set; } + private AClientNetwork UnityNetwork { get; set; } + /// + /// 创建一个Unity的Scene,注意:该方法只能在主线程下使用。 + /// + /// 选择Scene的运行方式 + /// + /// + public static async UniTask Create(string sceneRuntimeType = SceneRuntimeType.MainThread) + { + var world = ++_unityWorldId; + + if (world > byte.MaxValue - 1) + { + throw new Exception($"World ID ({world}) exceeds the maximum allowed value of 255."); + } + + var sceneId = (uint)(++_unitySceneId + world * 1000); + + if (sceneId > 255255) + { + throw new Exception($"Scene ID ({sceneId}) exceeds the maximum allowed value of 255255."); + } + + var scene = new Scene(); + scene.Scene = scene; + scene.Parent = scene; + scene.Type = typeof(Scene); + scene.EntityIdFactory = new EntityIdFactory(sceneId, world); + scene.RuntimeIdFactory = new RuntimeIdFactory(sceneId, world); + scene.Id = new EntityIdStruct(0, sceneId, world, 0); + scene.RuntimeId = new RuntimeIdStruct(0, sceneId, world, 0); + scene.AddEntity(scene); + await SetScheduler(scene, sceneRuntimeType); + scene.ThreadSynchronizationContext.Post(() => + { + scene.EventComponent.PublishAsync(new OnCreateScene(scene)).Forget(); + }); + return scene; + } + public Session Connect(string remoteAddress, NetworkProtocolType networkProtocolType, Action onConnectComplete, Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000) + { + UnityNetwork?.Dispose(); + UnityNetwork = NetworkProtocolFactory.CreateClient(this, networkProtocolType, NetworkTarget.Outer); + Session = UnityNetwork.Connect(remoteAddress, onConnectComplete, onConnectFail, onConnectDisconnect, isHttps, connectTimeout); + return Session; + } +#endif +#if FANTASY_NET + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Scene Create(Process process, byte worldId, uint sceneConfigId) + { + var scene = new Scene(); + scene.Scene = scene; + scene.Parent = scene; + scene.Type = typeof(Scene); + scene.Process = process; + scene.EntityIdFactory = new EntityIdFactory(sceneConfigId, worldId); + scene.RuntimeIdFactory = new RuntimeIdFactory(sceneConfigId, worldId); + scene.Id = new EntityIdStruct(0, sceneConfigId, worldId, 0); + scene.RuntimeId = new RuntimeIdStruct(0, sceneConfigId, worldId, 0); + scene.AddEntity(scene); + return scene; + } + /// + /// 创建一个新的Scene + /// + /// 所属的Process + /// 对应的MachineConfig配置文件 + /// 对应的SceneConfig配置文件 + /// 创建成功后会返回创建的Scene的实例 + public static async FTask Create(Process process, MachineConfig machineConfig, SceneConfig sceneConfig) + { + var scene = Create(process, (byte)sceneConfig.WorldConfigId, sceneConfig.Id); + scene.SceneType = sceneConfig.SceneType; + scene.SceneConfigId = sceneConfig.Id; + await SetScheduler(scene, sceneConfig.SceneRuntimeType); + + if (sceneConfig.WorldConfigId != 0) + { + scene.World = World.Create(scene, (byte)sceneConfig.WorldConfigId); + } + + if (sceneConfig.InnerPort != 0) + { + // 创建内网网络服务器 + scene.InnerNetwork = NetworkProtocolFactory.CreateServer(scene, ProcessDefine.InnerNetwork, NetworkTarget.Inner, machineConfig.InnerBindIP, sceneConfig.InnerPort); + } + + if (sceneConfig.OuterPort != 0) + { + // 创建外网网络服务 + var networkProtocolType = Enum.Parse(sceneConfig.NetworkProtocol); + scene.OuterNetwork = NetworkProtocolFactory.CreateServer(scene, networkProtocolType, NetworkTarget.Outer, machineConfig.OuterBindIP, sceneConfig.OuterPort); + } + Process.AddScene(scene); + process.AddSceneToProcess(scene); + scene.ThreadSynchronizationContext.Post(() => + { + if (sceneConfig.SceneTypeString == "Addressable") + { + // 如果是AddressableScene,自动添加上AddressableManageComponent。 + scene.AddComponent(); + } + + scene.EventComponent.PublishAsync(new OnCreateScene(scene)).Coroutine(); + }); + return scene; + } + /// + /// 在Scene下面创建一个子Scene,一般用于副本,或者一些特殊的场景。 + /// + /// 主Scene的实例 + /// SceneType,可以在SceneType里找到,例如:SceneType.Addressable + /// 子Scene创建成功后执行的委托,可以传递null + /// + public static SubScene CreateSubScene(Scene parentScene, int sceneType, Action onSubSceneComplete = null) + { + var scene = new SubScene(); + scene.Scene = scene; + scene.Parent = scene; + scene.RootScene = parentScene; + scene.Type = typeof(Scene); + scene.SceneType = sceneType; + scene.World = parentScene.World; + scene.Process = parentScene.Process; + scene.EntityIdFactory = parentScene.EntityIdFactory; + scene.RuntimeIdFactory = parentScene.RuntimeIdFactory; + scene.Id = scene.EntityIdFactory.Create; + scene.RuntimeId = scene.RuntimeIdFactory.Create; + scene.AddEntity(scene); + scene.Initialize(parentScene); + scene.ThreadSynchronizationContext.Post(() => OnEvent().Coroutine()); + return scene; + async FTask OnEvent() + { + await scene.EventComponent.PublishAsync(new OnCreateScene(scene)); + onSubSceneComplete?.Invoke(scene, parentScene); + } + } +#endif + private static async UniTask SetScheduler(Scene scene, string sceneRuntimeType) + { + switch (sceneRuntimeType) + { + case "MainThread": + { + scene.ThreadSynchronizationContext = ThreadScheduler.MainScheduler.ThreadSynchronizationContext; + scene.SceneUpdate = new EmptySceneUpdate(); + ThreadScheduler.AddMainScheduler(scene); + await scene.Initialize(); + break; + } + case "MultiThread": + { +#if !FANTASY_WEBGL + scene.ThreadSynchronizationContext = new ThreadSynchronizationContext(); +#endif + scene.SceneUpdate = new EmptySceneUpdate(); + ThreadScheduler.AddToMultiThreadScheduler(scene); + await scene.Initialize(); + break; + } + case "ThreadPool": + { +#if !FANTASY_WEBGL + scene.ThreadSynchronizationContext = new ThreadSynchronizationContext(); +#endif + scene.SceneUpdate = new EmptySceneUpdate(); + ThreadScheduler.AddToThreadPoolScheduler(scene); + await scene.Initialize(); + break; + } + } + } + #endregion + + #region Entities + + /// + /// 添加一个实体到当前Scene下 + /// + /// 实体实例 + public virtual void AddEntity(Entity entity) + { + Entities.Add(entity.RuntimeId, entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 返回的实体 + public virtual Entity GetEntity(long runTimeId) + { + return Entities.TryGetValue(runTimeId, out var entity) ? entity : null; + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 返回一个bool值来提示是否查找到这个实体 + public virtual bool TryGetEntity(long runTimeId, out Entity entity) + { + return Entities.TryGetValue(runTimeId, out entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 要查询实体的泛型类型 + /// 返回的实体 + public virtual T GetEntity(long runTimeId) where T : Entity + { + return Entities.TryGetValue(runTimeId, out var entity) ? (T)entity : null; + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 要查询实体的泛型类型 + /// 返回一个bool值来提示是否查找到这个实体 + public virtual bool TryGetEntity(long runTimeId, out T entity) where T : Entity + { + if (Entities.TryGetValue(runTimeId, out var getEntity)) + { + entity = (T)getEntity; + return true; + } + + entity = null; + return false; + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体的RunTimeId + /// 返回一个bool值来提示是否删除了这个实体 + public virtual bool RemoveEntity(long runTimeId) + { + return Entities.Remove(runTimeId); + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体实例 + /// 返回一个bool值来提示是否删除了这个实体 + public virtual bool RemoveEntity(Entity entity) + { + return Entities.Remove(entity.RuntimeId); + } + + #endregion + + #region InnerSession + +#if FANTASY_NET + /// + /// 根据runTimeId获得Session + /// + /// + /// + /// + public virtual Session GetSession(long runTimeId) + { + var sceneId = RuntimeIdFactory.GetSceneId(ref runTimeId); + + if (_processSessionInfos.TryGetValue(sceneId, out var processSessionInfo)) + { + if (!processSessionInfo.Session.IsDisposed) + { + return processSessionInfo.Session; + } + + _processSessionInfos.Remove(sceneId); + } + + if (Process.IsInAppliaction(ref sceneId)) + { + // 如果在同一个Process下,不需要通过Socket发送了,直接通过Process下转发。 + var processSession = Session.CreateInnerSession(Scene); + _processSessionInfos.Add(sceneId, new ProcessSessionInfo(processSession, null)); + return processSession; + } + + if (!SceneConfigData.Instance.TryGet(sceneId, out var sceneConfig)) + { + throw new Exception($"The scene with sceneId {sceneId} was not found in the configuration file"); + } + + if (!ProcessConfigData.Instance.TryGet(sceneConfig.ProcessConfigId, out var processConfig)) + { + throw new Exception($"The process with processId {sceneConfig.ProcessConfigId} was not found in the configuration file"); + } + + if (!MachineConfigData.Instance.TryGet(processConfig.MachineId, out var machineConfig)) + { + throw new Exception($"The machine with machineId {processConfig.MachineId} was not found in the configuration file"); + } + + var remoteAddress = $"{machineConfig.InnerBindIP}:{sceneConfig.InnerPort}"; + var client = NetworkProtocolFactory.CreateClient(Scene, ProcessDefine.InnerNetwork, NetworkTarget.Inner); + var session = client.Connect(remoteAddress, null, () => + { + Log.Error($"Unable to connect to the target server sourceServerId:{Scene.Process.Id} targetServerId:{sceneConfig.ProcessConfigId}"); + }, null, false); + _processSessionInfos.Add(sceneId, new ProcessSessionInfo(session, client)); + return session; + } +#endif + #endregion + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scene.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scene.cs.meta new file mode 100644 index 00000000..1d3f9972 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 968a867914cca474581795824737b521 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SceneRuntimeType.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SceneRuntimeType.cs new file mode 100644 index 00000000..f22e11ae --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SceneRuntimeType.cs @@ -0,0 +1,21 @@ +namespace Fantasy +{ + /// + /// Scene的运行类型 + /// + public class SceneRuntimeType + { + /// + /// Scene在主线程中运行. + /// + public const string MainThread = "MainThread"; + /// + /// Scene在一个独立的线程中运行. + /// + public const string MultiThread = "MultiThread"; + /// + /// Scene在一个根据当前CPU核心数创建的线程池中运行. + /// + public const string ThreadPool = "ThreadPool"; + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SceneRuntimeType.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SceneRuntimeType.cs.meta new file mode 100644 index 00000000..d0481cf3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SceneRuntimeType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fce1a72d9b59c4611b4355bc1246a582 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler.meta new file mode 100644 index 00000000..21b0c924 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 430e21e71c301427fb3a568d44ec6afa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ISceneScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ISceneScheduler.cs new file mode 100644 index 00000000..c04cc302 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ISceneScheduler.cs @@ -0,0 +1,11 @@ +using System; + +namespace Fantasy +{ + internal interface ISceneScheduler : IDisposable + { + void Add(Scene scene); + void Remove(Scene scene); + void Update(); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ISceneScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ISceneScheduler.cs.meta new file mode 100644 index 00000000..0d3c3720 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ISceneScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f39eba01f7f4a4b4eb94287997144b26 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MainScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MainScheduler.cs new file mode 100644 index 00000000..692def0e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MainScheduler.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +#if FANTASY_UNITY || FANTASY_NET || !FANTASY_WEBGL +using System.Threading; +#endif +#if FANTASY_NET +using Fantasy.Platform.Net; +#endif +namespace Fantasy +{ + internal sealed class MainScheduler : ISceneScheduler + { + private readonly Queue _queue = new Queue(); + public readonly ThreadSynchronizationContext ThreadSynchronizationContext; + + public MainScheduler() + { + ThreadSynchronizationContext = new ThreadSynchronizationContext(); +#if !FANTASY_WEBGL + SynchronizationContext.SetSynchronizationContext(ThreadSynchronizationContext); +#endif + } + public void Dispose() + { + _queue.Clear(); + } + + public void Add(Scene scene) + { + ThreadSynchronizationContext.Post(() => + { + if (scene.IsDisposed) + { + return; + } + + _queue.Enqueue(scene); + }); + } + + public void Remove(Scene scene) + { + ThreadSynchronizationContext.Post(() => + { + if (scene.IsDisposed) + { + return; + } + + var initialCount = _queue.Count; + for (var i = 0; i < initialCount; i++) + { + var currentScene = _queue.Dequeue(); + if (currentScene != scene) + { + _queue.Enqueue(currentScene); + } + } + }); + } + + public void Update() + { + ThreadSynchronizationContext.Update(); + var initialCount = _queue.Count; + + while (initialCount-- > 0) + { + if(!_queue.TryDequeue(out var scene)) + { + continue; + } + + if (scene.IsDisposed) + { + continue; + } + + scene.Update(); + _queue.Enqueue(scene); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MainScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MainScheduler.cs.meta new file mode 100644 index 00000000..b2dba504 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MainScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c7398438bdaa4c1aa3ae9bd545acc76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MultiThreadScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MultiThreadScheduler.cs new file mode 100644 index 00000000..28f2d42b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MultiThreadScheduler.cs @@ -0,0 +1,103 @@ +#if !FANTASY_WEBGL || !FANTASY_SINGLETHREAD +using System; +using System.Collections.Concurrent; +using System.Threading; +namespace Fantasy +{ + internal struct MultiThreadStruct : IDisposable + { + public readonly Thread Thread; + public readonly CancellationTokenSource Cts; + + public MultiThreadStruct(Thread thread, CancellationTokenSource cts) + { + Thread = thread; + Cts = cts; + } + + public void Dispose() + { + Cts.Cancel(); + if (Thread.IsAlive) + { + Thread.Join(); + } + Cts.Dispose(); + } + } + + internal sealed class MultiThreadScheduler : ISceneScheduler + { + private bool _isDisposed; + private readonly ConcurrentDictionary _threads = new ConcurrentDictionary(); + public int ThreadCount => _threads.Count; + + public void Dispose() + { + if (_isDisposed) + { + return; + } + + _isDisposed = true; + + foreach (var (_, multiThreadStruct) in _threads.ToArray()) + { + multiThreadStruct.Dispose(); + } + + _threads.Clear(); + } + + public void Add(Scene scene) + { + var cts = new CancellationTokenSource(); + var thread = new Thread(() => Loop(scene, cts.Token)); + _threads.TryAdd(scene.RuntimeId, new MultiThreadStruct(thread, cts)); + thread.Start(); + } + + public void Remove(Scene scene) + { + if (_threads.TryRemove(scene.RuntimeId, out var multiThreadStruct)) + { + multiThreadStruct.Dispose(); + } + } + + public void Update() + { + throw new NotImplementedException(); + } + + private void Loop(Scene scene, CancellationToken cancellationToken) + { + var sceneThreadSynchronizationContext = scene.ThreadSynchronizationContext; + SynchronizationContext.SetSynchronizationContext(sceneThreadSynchronizationContext); + + while (!cancellationToken.IsCancellationRequested) + { + try + { + if (scene.IsDisposed) + { + Remove(scene); + return; + } + + sceneThreadSynchronizationContext.Update(); + scene.Update(); + } + catch (Exception e) + { + Log.Error($"Error in MultiThreadScheduler loop: {e.Message}"); + } + finally + { + Thread.Sleep(1); + } + } + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta new file mode 100644 index 00000000..3547e95d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/MultiThreadScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36b6da87c3a674cb5b2d2d9d270c397d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadPoolScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadPoolScheduler.cs new file mode 100644 index 00000000..9f5a44c9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadPoolScheduler.cs @@ -0,0 +1,140 @@ +#if !FANTASY_WEBGL || !FANTASY_SINGLETHREAD +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8604 // Possible null reference argument. +namespace Fantasy +{ + internal sealed class ThreadPoolScheduler : ISceneScheduler + { + private bool _isDisposed; + private readonly List _threads; + private readonly ConcurrentBag _queue = new ConcurrentBag(); + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + + public ThreadPoolScheduler() + { + // 最大线程数、避免线程过多发生的资源抢占问题。 + // 但如果使用了MultiThreadScheduler,那么这里的线程数就算是设置了也有可能导致线程过多的问题。 + // 线程过多看每个线程的抢占情况,如果抢占资源占用不是很大也没什么大问题。如果过大的情况,就会有性能问题。 + // 所以根据情况来使用不同的调度器。 + var maxThreadCount = Environment.ProcessorCount; + _threads = new List(maxThreadCount); + + for (var i = 0; i < maxThreadCount; ++i) + { + Thread thread = new(() => Loop(_cancellationTokenSource.Token)) + { + IsBackground = true + }; + _threads.Add(thread); + thread.Start(); + } + } + + public void Dispose() + { + if (_isDisposed) + { + return; + } + + _isDisposed = true; + _cancellationTokenSource.Cancel(); + + foreach (var thread in _threads) + { + if (thread.IsAlive) + { + thread.Join(); + } + } + + _cancellationTokenSource.Dispose(); + _threads.Clear(); + } + + public void Add(Scene scene) + { + if (_isDisposed) + { + return; + } + + _queue.Add(scene); + } + + public void Remove(Scene scene) + { + if (_isDisposed) + { + return; + } + + var newQueue = new Queue(); + + while (!_queue.IsEmpty) + { + if (_queue.TryTake(out var currentScene)) + { + if (currentScene != scene) + { + newQueue.Enqueue(currentScene); + } + } + } + + while (newQueue.TryDequeue(out var newScene)) + { + _queue.Add(newScene); + } + } + + public void Update() + { + throw new NotImplementedException(); + } + + private void Loop(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + if (_queue.TryTake(out var scene)) + { + if (scene == null || scene.IsDisposed) + { + continue; + } + + var sceneThreadSynchronizationContext = scene.ThreadSynchronizationContext; + SynchronizationContext.SetSynchronizationContext(sceneThreadSynchronizationContext); + + try + { + sceneThreadSynchronizationContext.Update(); + scene.Update(); + } + catch (Exception e) + { + Log.Error($"Error in ThreadPoolScheduler scene: {e.Message}"); + } + finally + { + SynchronizationContext.SetSynchronizationContext(null); + } + + _queue.Add(scene); + Thread.Sleep(1); + } + else + { + // 当队列为空的时候、避免无效循环消耗CPU。 + Thread.Sleep(10); + } + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta new file mode 100644 index 00000000..e263f943 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadPoolScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 12f33fe68e2b64ac98ecd79b8158e420 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadScheduler.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadScheduler.cs new file mode 100644 index 00000000..5bd0dea3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadScheduler.cs @@ -0,0 +1,66 @@ +// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +namespace Fantasy +{ + /// + /// 线程调度器 + /// + internal static class ThreadScheduler + { + /// + /// 主线程调度器 + /// + public static MainScheduler MainScheduler { get; private set; } + /// + /// 多线程调度器,根据当前CPU核心数量创建的固定线程。 + /// + public static ISceneScheduler MultiThreadScheduler { get; private set; } + /// + /// 线程池调度器 + /// + public static ISceneScheduler ThreadPoolScheduler { get; private set; } + + static ThreadScheduler() + { + MainScheduler = new MainScheduler(); + } + + internal static void Update() + { + MainScheduler.Update(); + } + + internal static void AddMainScheduler(Scene scene) + { + MainScheduler.Add(scene); + } + + internal static void AddToMultiThreadScheduler(Scene scene) + { + if (MultiThreadScheduler == null) + { +#if FANTASY_SINGLETHREAD || FANTASY_WEBGL + MultiThreadScheduler = MainScheduler; +#else + MultiThreadScheduler = new MultiThreadScheduler(); +#endif + } + + MultiThreadScheduler.Add(scene); + } + + internal static void AddToThreadPoolScheduler(Scene scene) + { + if (ThreadPoolScheduler == null) + { +#if FANTASY_SINGLETHREAD || FANTASY_WEBGL + ThreadPoolScheduler = MainScheduler; +#else + ThreadPoolScheduler = new ThreadPoolScheduler(); +#endif + } + + ThreadPoolScheduler.Add(scene); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadScheduler.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadScheduler.cs.meta new file mode 100644 index 00000000..476a3b7c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/Scheduler/ThreadScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d9807e33a9ca94371885c6934ff42523 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SubScene.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SubScene.cs new file mode 100644 index 00000000..1c52918c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SubScene.cs @@ -0,0 +1,147 @@ +using System.Runtime.Serialization; +using Fantasy.Entitas; +using Newtonsoft.Json; +using Fantasy.Network; +using MongoDB.Bson.Serialization.Attributes; +using ProtoBuf; + +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. + +namespace Fantasy +{ + /// + /// 代表一个Scene下的子Scene + /// + public sealed partial class SubScene : Scene + { + /// + /// 当前子Scene的父Scene + /// + [BsonIgnore] + [JsonIgnore] + [ProtoIgnore] + [IgnoreDataMember] + public Scene RootScene { get; internal set; } + + internal void Initialize(Scene rootScene) + { + EntityPool = rootScene.EntityPool; + EntityListPool = rootScene.EntityListPool; + EntitySortedDictionaryPool = rootScene.EntitySortedDictionaryPool; + SceneUpdate = rootScene.SceneUpdate; + TimerComponent = rootScene.TimerComponent; + EventComponent = rootScene.EventComponent; + EntityComponent = rootScene.EntityComponent; + MessagePoolComponent = rootScene.MessagePoolComponent; + CoroutineLockComponent = rootScene.CoroutineLockComponent; + MessageDispatcherComponent = rootScene.MessageDispatcherComponent; + NetworkMessagingComponent = rootScene.NetworkMessagingComponent; + #if FANTASY_NET + SingleCollectionComponent = rootScene.SingleCollectionComponent; + #endif + ThreadSynchronizationContext = rootScene.ThreadSynchronizationContext; + } + + /// + /// 子Scene的销毁方法 + /// + public override void Dispose() + { + if (IsDisposed) + { + return; + } + + RootScene.RemoveEntity(RuntimeId); + RootScene = null; + base.Dispose(); + } + + /// + /// 添加一个实体到当前Scene下 + /// + /// 实体实例 + public override void AddEntity(Entity entity) + { + RootScene.AddEntity(entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 返回的实体 + public override Entity GetEntity(long runTimeId) + { + return RootScene.GetEntity(runTimeId); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 返回一个bool值来提示是否查找到这个实体 + public override bool TryGetEntity(long runTimeId, out Entity entity) + { + return RootScene.TryGetEntity(runTimeId, out entity); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 要查询实体的泛型类型 + /// 返回的实体 + public override T GetEntity(long runTimeId) + { + return RootScene.GetEntity(runTimeId); + } + + /// + /// 根据RunTimeId查询一个实体 + /// + /// 实体的RunTimeId + /// 实体实例 + /// 要查询实体的泛型类型 + /// 返回一个bool值来提示是否查找到这个实体 + public override bool TryGetEntity(long runTimeId, out T entity) + { + return RootScene.TryGetEntity(runTimeId, out entity); + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体的RunTimeId + /// 返回一个bool值来提示是否删除了这个实体 + public override bool RemoveEntity(long runTimeId) + { + return RootScene.RemoveEntity(runTimeId); + } + + /// + /// 删除一个实体,仅是删除不会指定实体的销毁方法 + /// + /// 实体实例 + /// 返回一个bool值来提示是否删除了这个实体 + public override bool RemoveEntity(Entity entity) + { + return RootScene.RemoveEntity(entity); + } + +#if FANTASY_NET + /// + /// 根据runTimeId获得Session + /// + /// + /// + /// + public override Session GetSession(long runTimeId) + { + return RootScene.GetSession(runTimeId); + } + #endif + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SubScene.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SubScene.cs.meta new file mode 100644 index 00000000..9e9bd5d6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Scene/SubScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38f07f37ebbca4379903da052249b06b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize.meta new file mode 100644 index 00000000..5ded792f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: acd70d541dd3b4be5a68d4508bc5d5e3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack.meta new file mode 100644 index 00000000..1617db2b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0a19189e3038447bb88d6d991d3f1228 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/BsonPackHelper.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/BsonPackHelper.cs new file mode 100644 index 00000000..6f9169f7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/BsonPackHelper.cs @@ -0,0 +1,372 @@ +#if FANTASY_UNITY +using System; +using System.Buffers; +namespace Fantasy.Serialize +{ + public class BsonPackHelper : ISerialize + { + public string SerializeName { get; } = "Bson"; + public T Deserialize(byte[] bytes) + { + throw new NotImplementedException(); + } + + public T Deserialize(MemoryStreamBuffer buffer) + { + throw new NotImplementedException(); + } + + public object Deserialize(Type type, byte[] bytes) + { + throw new NotImplementedException(); + } + + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + throw new NotImplementedException(); + } + + public T Deserialize(byte[] bytes, int index, int count) + { + throw new NotImplementedException(); + } + + public object Deserialize(Type type, byte[] bytes, int index, int count) + { + throw new NotImplementedException(); + } + + public void Serialize(T @object, IBufferWriter buffer) + { + throw new NotImplementedException(); + } + + public void Serialize(object @object, IBufferWriter buffer) + { + throw new NotImplementedException(); + } + + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + throw new NotImplementedException(); + } + + public T Clone(T t) + { + throw new NotImplementedException(); + } + } +} +#endif + +#if FANTASY_NET +using System.Buffers; +using System.Collections; +using System.ComponentModel; +using System.Reflection; +using Fantasy.Assembly; +using Fantasy.Entitas; +using MongoDB.Bson; +using MongoDB.Bson.IO; +using MongoDB.Bson.Serialization; +using MongoDB.Bson.Serialization.Conventions; +using MongoDB.Bson.Serialization.Serializers; +#pragma warning disable CS8603 // Possible null reference return. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. + +namespace Fantasy.Serialize +{ + /// + /// BSON帮助方法 + /// + public class BsonPackHelper : ISerialize + { + /// + /// 序列化器的名字 + /// + public string SerializeName { get; } = "Bson"; + + /// + /// 构造函数 + /// + public BsonPackHelper() + { + // 清除掉注册过的LookupClassMap。 + + var classMapRegistryField = typeof(BsonClassMap).GetField("__classMaps", BindingFlags.Static | BindingFlags.NonPublic); + + if (classMapRegistryField != null) + { + ((Dictionary)classMapRegistryField.GetValue(null)).Clear(); + } + + // 清除掉注册过的ConventionRegistry。 + + var registryField = typeof(ConventionRegistry).GetField("_lookup", BindingFlags.Static | BindingFlags.NonPublic); + + if (registryField != null) + { + var registry = registryField.GetValue(null); + var dictionaryField = registry.GetType().GetField("_conventions", BindingFlags.Instance | BindingFlags.NonPublic); + if (dictionaryField != null) + { + ((IDictionary)dictionaryField.GetValue(registry)).Clear(); + } + } + + // 初始化ConventionRegistry、注册IgnoreExtraElements。 + + ConventionRegistry.Register("IgnoreExtraElements", new ConventionPack { new IgnoreExtraElementsConvention(true) }, type => true); + + // 注册一个自定义的序列化器。 + + // BsonSerializer.TryRegisterSerializer(typeof(float2), new StructBsonSerialize()); + // BsonSerializer.TryRegisterSerializer(typeof(float3), new StructBsonSerialize()); + // BsonSerializer.TryRegisterSerializer(typeof(float4), new StructBsonSerialize()); + // BsonSerializer.TryRegisterSerializer(typeof(quaternion), new StructBsonSerialize()); + BsonSerializer.RegisterSerializer(new ObjectSerializer(x => true)); + + // 注册LookupClassMap。 + + foreach (var type in AssemblySystem.ForEach()) + { + if (type.IsInterface || type.IsAbstract || type.IsGenericType || !typeof(Entity).IsAssignableFrom(type)) + { + continue; + } + + BsonClassMap.LookupClassMap(type); + } + } + + /// + /// 反序列化 + /// + /// + /// + /// + public T Deserialize(byte[] bytes) + { + var @object = BsonSerializer.Deserialize(bytes); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + public T Deserialize(MemoryStreamBuffer buffer) + { + var @object = BsonSerializer.Deserialize(buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + public object Deserialize(Type type, byte[] bytes) + { + var @object = BsonSerializer.Deserialize(bytes, type); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + var @object = BsonSerializer.Deserialize(buffer, type); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + public unsafe T Deserialize(byte[] bytes, int index, int count) + { + T @object; + + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + @object = BsonSerializer.Deserialize(stream); + } + + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + public unsafe object Deserialize(Type type, byte[] bytes, int index, int count) + { + object @object; + + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + @object = BsonSerializer.Deserialize(stream, type); + } + + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + + /// + /// 序列化 + /// + /// + /// + /// + public void Serialize(T @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = + new BsonBinaryWriter((MemoryStream)buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, @object); + } + + /// + /// 序列化 + /// + /// + /// + public void Serialize(object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = + new BsonBinaryWriter((MemoryStream)buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, @object.GetType(), @object); + } + + /// + /// 序列化 + /// + /// + /// + /// + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = + new BsonBinaryWriter((MemoryStream)buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, type, @object); + } + + /// + /// 序列化并返回的长度 + /// + /// + /// + /// + /// + public int SerializeAndReturnLength(Type type, object @object, MemoryStreamBuffer buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + using IBsonWriter bsonWriter = new BsonBinaryWriter(buffer, BsonBinaryWriterSettings.Defaults); + BsonSerializer.Serialize(bsonWriter, type, @object); + return (int)buffer.Length; + } + + /// + /// 序列化 + /// + /// + /// + public static byte[] Serialize(object @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + return @object.ToBson(@object.GetType()); + } + + /// + /// 序列化 + /// + /// + /// + /// + public static byte[] Serialize(T @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + return @object.ToBson(); + } + + /// + /// 克隆 + /// + /// + /// + /// + public T Clone(T t) + { + return Deserialize(Serialize(t)); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/BsonPackHelper.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/BsonPackHelper.cs.meta new file mode 100644 index 00000000..ddeaf945 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/BsonPackHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64ec3897de5274b708e95c740aea9de4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/StructBsonSerialize.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/StructBsonSerialize.cs new file mode 100644 index 00000000..15d8663b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/StructBsonSerialize.cs @@ -0,0 +1,65 @@ +#if FANTASY_NET +using System.Reflection; +using MongoDB.Bson; +using MongoDB.Bson.IO; +using MongoDB.Bson.Serialization; +using MongoDB.Bson.Serialization.Serializers; + +namespace Fantasy.Serialize; + +/// +/// 提供对结构体类型进行 BSON 序列化和反序列化的辅助类。 +/// +/// 要序列化和反序列化的结构体类型。 +public class StructBsonSerialize : StructSerializerBase where TValue : struct +{ + /// + /// 将结构体对象序列化为 BSON 数据。 + /// + /// 序列化上下文。 + /// 序列化参数。 + /// 要序列化的结构体对象。 + public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value) + { + var nominalType = args.NominalType; + var bsonWriter = context.Writer; + bsonWriter.WriteStartDocument(); + var fields = nominalType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + foreach (var field in fields) + { + bsonWriter.WriteName(field.Name); + BsonSerializer.Serialize(bsonWriter, field.FieldType, field.GetValue(value)); + } + bsonWriter.WriteEndDocument(); + } + + /// + /// 将 BSON 数据反序列化为结构体对象。 + /// + /// 反序列化上下文。 + /// 反序列化参数。 + /// 反序列化得到的结构体对象。 + public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) + { + //boxing is required for SetValue to work + object obj = new TValue(); + var actualType = args.NominalType; + var bsonReader = context.Reader; + bsonReader.ReadStartDocument(); + while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) + { + var name = bsonReader.ReadName(Utf8NameDecoder.Instance); + + var field = actualType.GetField(name, + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (field != null) + { + var value = BsonSerializer.Deserialize(bsonReader, field.FieldType); + field.SetValue(obj, value); + } + } + bsonReader.ReadEndDocument(); + return (TValue) obj; + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta new file mode 100644 index 00000000..3864af5b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/StructBsonSerialize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3965973989a254244818a3db5ba1d9fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/SupportInitializeChecker.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/SupportInitializeChecker.cs new file mode 100644 index 00000000..82c68291 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/SupportInitializeChecker.cs @@ -0,0 +1,17 @@ +#if FANTASY_NET +using System.ComponentModel; +using Fantasy.Entitas; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Serialize; + +public static class SupportInitializeChecker where T : Entity +{ + public static bool IsSupported { get; } + + static SupportInitializeChecker() + { + IsSupported = typeof(ISupportInitialize).IsAssignableFrom(typeof(T)); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta new file mode 100644 index 00000000..b87cfa65 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/BsonPack/SupportInitializeChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6d731a2f55db4fa08667dc8195cd49a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface.meta new file mode 100644 index 00000000..817a2007 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 67cee2b81543348e8b18e5425e0e4863 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ASerialize.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ASerialize.cs new file mode 100644 index 00000000..7487b86d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ASerialize.cs @@ -0,0 +1,60 @@ +using System; +using System.ComponentModel; +using System.Runtime.Serialization; +using Fantasy.Pool; +#if FANTASY_NET || FANTASY_UNITY || FANTASY_CONSOLE +using MongoDB.Bson.Serialization.Attributes; +#endif +using Newtonsoft.Json; +using ProtoBuf; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + +namespace Fantasy.Serialize +{ + public abstract class ASerialize : ISupportInitialize, IDisposable + { + public virtual void Dispose() { } + public virtual void BeginInit() { } + public virtual void EndInit() { } + public virtual void AfterDeserialization() => EndInit(); + } + + public abstract class AMessage : ASerialize, IPool + { +#if FANTASY_NET || FANTASY_UNITY || FANTASY_CONSOLE + [BsonIgnore] + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + private Scene _scene; + protected Scene GetScene() + { + return _scene; + } + + public void SetScene(Scene scene) + { + _scene = scene; + } +#endif +#if FANTASY_NET + [BsonIgnore] +#endif + [JsonIgnore] + [IgnoreDataMember] + [ProtoIgnore] + private bool _isPool; + + public bool IsPool() + { + return _isPool; + } + + public void SetIsPool(bool isPool) + { + _isPool = isPool; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ASerialize.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ASerialize.cs.meta new file mode 100644 index 00000000..9ab76f23 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ASerialize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0d1f037ce81346e8a04a78f128b0e65 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ISerialize.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ISerialize.cs new file mode 100644 index 00000000..a3a91590 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ISerialize.cs @@ -0,0 +1,87 @@ +using System; +using System.Buffers; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +namespace Fantasy.Serialize +{ + public interface ISerialize + { + /// + /// 序列化器的名字,用于在协议里指定用什么协议序列化使用 + /// + string SerializeName { get; } + /// + /// 反序列化 + /// + /// + /// + /// + T Deserialize(byte[] bytes); + /// + /// 反序列化 + /// + /// + /// + /// + T Deserialize(MemoryStreamBuffer buffer); + /// + /// 反序列化 + /// + /// + /// + /// + object Deserialize(Type type, byte[] bytes); + /// + /// 反序列化 + /// + /// + /// + /// + object Deserialize(Type type, MemoryStreamBuffer buffer); + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + T Deserialize(byte[] bytes, int index, int count); + /// + /// 反序列化 + /// + /// + /// + /// + /// + /// + object Deserialize(Type type, byte[] bytes, int index, int count); + /// + /// 序列化 + /// + /// + /// + /// + void Serialize(T @object, IBufferWriter buffer); + /// + /// 序列化 + /// + /// + /// + void Serialize(object @object, IBufferWriter buffer); + /// + /// 序列化 + /// + /// + /// + /// + void Serialize(Type type, object @object, IBufferWriter buffer); + /// + /// 克隆 + /// + /// + /// + /// + T Clone(T t); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ISerialize.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ISerialize.cs.meta new file mode 100644 index 00000000..e492336c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/Interface/ISerialize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a7d62fda7ac04f3fb7d1fd6955da409 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/MemoryStreamBuffer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/MemoryStreamBuffer.cs new file mode 100644 index 00000000..d3176f12 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/MemoryStreamBuffer.cs @@ -0,0 +1,71 @@ +using System; +using System.Buffers; +using System.IO; +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +namespace Fantasy.Serialize +{ + public enum MemoryStreamBufferSource + { + None = 0, + Pack = 1, + UnPack = 2, + } + + public sealed class MemoryStreamBuffer : MemoryStream, IBufferWriter + { + public MemoryStreamBufferSource MemoryStreamBufferSource; + public MemoryStreamBuffer() { } + + public MemoryStreamBuffer(MemoryStreamBufferSource memoryStreamBufferSource, int capacity) : base(capacity) + { + MemoryStreamBufferSource = memoryStreamBufferSource; + } + public MemoryStreamBuffer(byte[] buffer): base(buffer) { } + + public void Advance(int count) + { + if (count < 0) + { + throw new ArgumentOutOfRangeException(nameof(count), count, "The value of 'count' cannot be negative."); + } + + var newLength = Position + count; + if (newLength > Length) + { + SetLength(newLength); + } + Position = newLength; + } + + public Memory GetMemory(int sizeHint = 0) + { + if (sizeHint < 0) + { + throw new ArgumentOutOfRangeException(nameof(sizeHint), sizeHint, "The value of 'count' cannot be negative."); + } + + if (Length - Position <= sizeHint) + { + SetLength(Position + sizeHint); + } + + return new Memory(GetBuffer(), (int)Position, (int)(Length - Position)); + } + + public Span GetSpan(int sizeHint = 0) + { + if (sizeHint < 0) + { + throw new ArgumentOutOfRangeException(nameof(sizeHint), sizeHint, "The value of 'count' cannot be negative."); + } + + if (Length - Position <= sizeHint) + { + SetLength(Position + sizeHint); + } + + return new Span(GetBuffer(), (int)Position, (int)(Length - Position)); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/MemoryStreamBuffer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/MemoryStreamBuffer.cs.meta new file mode 100644 index 00000000..21bbeed5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/MemoryStreamBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c6e3b5d66fc8451482eaf828663e6a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper.meta new file mode 100644 index 00000000..b414d6fa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0f56f731b0e9a4bdb931dce6773bc1e1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/IProto.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/IProto.cs new file mode 100644 index 00000000..2267dd24 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/IProto.cs @@ -0,0 +1,9 @@ +namespace Fantasy.Serialize +{ + /// + /// 代表是一个ProtoBuf协议 + /// + public interface IProto + { + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta new file mode 100644 index 00000000..eff98209 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/IProto.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8890f4dc3e2c433fbd22b91ead3bfe4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs new file mode 100644 index 00000000..af0c3aab --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs @@ -0,0 +1,221 @@ +using System.Buffers; +using Fantasy.Assembly; +using ProtoBuf.Meta; + +#if FANTASY_NET || FANTASY_EXPORTER +namespace Fantasy.Serialize +{ + /// + /// ProtoBufP帮助类,Net平台使用 + /// + public sealed class ProtoBufPackHelper : ISerialize + { + /// + /// 序列化器的名字 + /// + public string SerializeName { get; } = "ProtoBuf"; + + /// + /// 构造函数 + /// + public ProtoBufPackHelper () + { +#if FANTASY_NET + RuntimeTypeModel.Default.AutoAddMissingTypes = true; + RuntimeTypeModel.Default.AllowParseableTypes = true; + RuntimeTypeModel.Default.AutoAddMissingTypes = true; + RuntimeTypeModel.Default.AutoCompile = true; + RuntimeTypeModel.Default.UseImplicitZeroDefaults = true; + RuntimeTypeModel.Default.InferTagFromNameDefault = true; + + foreach (var type in AssemblySystem.ForEach(typeof(IProto))) + { + RuntimeTypeModel.Default.Add(type, true); + } + + RuntimeTypeModel.Default.CompileInPlace(); +#endif + } + + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public T Deserialize(byte[] bytes) + { + var memory = new ReadOnlyMemory(bytes); + var @object = RuntimeTypeModel.Default.Deserialize(memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public T Deserialize(MemoryStreamBuffer buffer) + { + var @object = RuntimeTypeModel.Default.Deserialize(buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public object Deserialize(Type type, byte[] bytes) + { + var memory = new ReadOnlyMemory(bytes); + var @object = RuntimeTypeModel.Default.Deserialize(type, memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + var @object = RuntimeTypeModel.Default.Deserialize(type, buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public T Deserialize(byte[] bytes, int index, int count) + { + var memory = new ReadOnlyMemory(bytes, index, count); + var @object = RuntimeTypeModel.Default.Deserialize(memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public object Deserialize(Type type, byte[] bytes, int index, int count) + { + var memory = new ReadOnlyMemory(bytes, index, count); + var @object = RuntimeTypeModel.Default.Deserialize(type, memory); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(T @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize(buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + public void Serialize(object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize(buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize(buffer, @object); + } + internal byte[] Serialize(object @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + var buffer = new MemoryStream(); + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + private byte[] Serialize(T @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + var buffer = new MemoryStream(); + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + /// + /// 克隆 + /// + /// + /// + /// + public T Clone(T t) + { + return Deserialize(Serialize(t)); + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta new file mode 100644 index 00000000..53783871 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperNet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d4c478636a67f47c0996ec35989d5b38 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs new file mode 100644 index 00000000..d04b6ba6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs @@ -0,0 +1,200 @@ +#if FANTASY_UNITY || FANTASY_CONSOLE +using System; +using System.Buffers; +using System.IO; +using Fantasy.Assembly; +using ProtoBuf; +using ProtoBuf.Meta; + +namespace Fantasy.Serialize +{ + /// + /// ProtoBufP帮助类,Unity平台使用 + /// + public sealed class ProtoBufPackHelper : ISerialize + { + /// + /// 序列化器的名字 + /// + public string SerializeName { get; } = "ProtoBuf"; + + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public unsafe T Deserialize(byte[] bytes) + { + fixed (byte* ptr = bytes) + { + using var stream = new UnmanagedMemoryStream(ptr, bytes.Length); + var @object = ProtoBuf.Serializer.Deserialize(stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public T Deserialize(MemoryStreamBuffer buffer) + { + var @object = ProtoBuf.Serializer.Deserialize(buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public unsafe object Deserialize(Type type, byte[] bytes) + { + fixed (byte* ptr = bytes) + { + using var stream = new UnmanagedMemoryStream(ptr, bytes.Length); + var @object = ProtoBuf.Serializer.Deserialize(type, stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + public object Deserialize(Type type, MemoryStreamBuffer buffer) + { + var @object = ProtoBuf.Serializer.Deserialize(type, buffer); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + + return @object; + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public unsafe T Deserialize(byte[] bytes, int index, int count) + { + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + var @object = ProtoBuf.Serializer.Deserialize(stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + } + /// + /// 使用ProtoBuf反序列化数据到实例 + /// + /// + /// + /// + /// + /// + public unsafe object Deserialize(Type type, byte[] bytes, int index, int count) + { + fixed (byte* ptr = &bytes[index]) + { + using var stream = new UnmanagedMemoryStream(ptr, count); + var @object = ProtoBuf.Serializer.Deserialize(type, stream); + if (@object is ASerialize aSerialize) + { + aSerialize.AfterDeserialization(); + } + return @object; + } + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(T @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize((MemoryStream)buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + public void Serialize(object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize((MemoryStream)buffer, @object); + } + /// + /// 使用ProtoBuf序列化某一个实例到IBufferWriter中 + /// + /// + /// + /// + public void Serialize(Type type, object @object, IBufferWriter buffer) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + RuntimeTypeModel.Default.Serialize((MemoryStream)buffer, @object); + } + private byte[] Serialize(T @object) + { + if (@object is ASerialize aSerialize) + { + aSerialize.BeginInit(); + } + + var buffer = new MemoryStream(); + RuntimeTypeModel.Default.Serialize(buffer, @object); + return buffer.ToArray(); + } + /// + /// 克隆 + /// + /// + /// + /// + public T Clone(T t) + { + return Deserialize(Serialize(t)); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta new file mode 100644 index 00000000..acf19ee7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/ProtoBufPackHelper/ProtoBufPackHelperUnity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b5e2bbc6d50014a4693df1cf25208d0d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/SerializerManager.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/SerializerManager.cs new file mode 100644 index 00000000..34e4f936 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/SerializerManager.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using Fantasy.Assembly; +using Fantasy.Helper; +#if !FANTASY_EXPORTER +using Fantasy.Network; +#endif +using ProtoBuf; +#pragma warning disable CS8604 // Possible null reference argument. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + +namespace Fantasy.Serialize +{ + /// + /// 框架内置的序列化器类型 + /// + public static class FantasySerializerType + { + /// + /// ProtoBuf在SerializerManager的数组下标 + /// + public const int ProtoBuf = 0; + /// + /// Bson在SerializerManager的数组下标 + /// + public const int Bson = 1; + } + + /// + /// 管理序列化静态方法,主要是优化网络协议时使用。 + /// + public static class SerializerManager + { + private static ISerialize[] _serializers; + private static bool _isInitialized = false; + +#if FANTASY_NET || FANTASY_UNITY + /// + /// 初始化方法 + /// + public static void Initialize() + { + if (_isInitialized) + { + return; + } + + try + { + var sort = new SortedList(); + + foreach (var serializerType in AssemblySystem.ForEach(typeof(ISerialize))) + { + var serializer = (ISerialize)Activator.CreateInstance(serializerType); + var computeHash64 = HashCodeHelper.ComputeHash64(serializer.SerializeName); + sort.Add(computeHash64, serializer); + } + + var index = 1; + _serializers = new ISerialize[sort.Count]; + + foreach (var (_, serialize) in sort) + { + var serializerIndex = 0; + + switch (serialize) + { + case ProtoBufPackHelper: + { + serializerIndex = FantasySerializerType.ProtoBuf; + break; + } + case BsonPackHelper: + { + serializerIndex = FantasySerializerType.Bson; + break; + } + default: + { + serializerIndex = ++index; + break; + } + } + + _serializers[serializerIndex] = serialize; + } + + _isInitialized = true; + } + catch + { + Dispose(); + throw; + } + } +#else + /// + /// 初始化方法 + /// + public static void Initialize() + { + if (_isInitialized) + { + return; + } + + _serializers = new ISerialize[1]; + _serializers[0] = new ProtoBufPackHelper(); + } +#endif + + /// + /// 销毁方法 + /// + public static void Dispose() + { + _isInitialized = false; + Array.Clear(_serializers, 0, _serializers.Length); + } + + /// + /// 根据协议类型获取序列化器 + /// + /// + /// + public static ISerialize GetSerializer(uint opCodeProtocolType) + { + return _serializers[opCodeProtocolType]; + } + + /// + /// 获得一个序列化器 + /// + /// + /// + /// + public static bool TryGetSerializer(uint opCodeProtocolType, out ISerialize serializer) + { + if (opCodeProtocolType < _serializers.Length) + { + serializer = _serializers[opCodeProtocolType]; + return true; + } + + serializer = default; + return false; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/SerializerManager.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/SerializerManager.cs.meta new file mode 100644 index 00000000..e4fd974b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Core/Serialize/SerializerManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 697ffcbc908194a5c9175595fd4e78e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins.meta new file mode 100644 index 00000000..84256f23 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9903bfee614344015878f1daf14b44de +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other.meta new file mode 100644 index 00000000..66d0161c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 66d4e7e54eaf44c4899b6a1ab0fea535 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Collections.Immutable.dll b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Collections.Immutable.dll new file mode 100644 index 00000000..30822887 Binary files /dev/null and b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Collections.Immutable.dll differ diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Collections.Immutable.dll.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Collections.Immutable.dll.meta new file mode 100644 index 00000000..1059b227 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Collections.Immutable.dll.meta @@ -0,0 +1,35 @@ +fileFormatVersion: 2 +guid: ce833409ea91b4422b820f1c70284317 +labels: +- NuGetForUnity +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.IO.Pipelines.dll b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.IO.Pipelines.dll new file mode 100644 index 00000000..003bcd00 Binary files /dev/null and b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.IO.Pipelines.dll differ diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.IO.Pipelines.dll.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.IO.Pipelines.dll.meta new file mode 100644 index 00000000..79090339 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.IO.Pipelines.dll.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 5ea484bad04534c33b3b128ff1e85ed3 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude WebGL: 0 + Exclude Win: 0 + Exclude Win64: 0 + Exclude iOS: 0 + - first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 1 + settings: + AddToEmbeddedBinaries: false + CPU: AnyCPU + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll new file mode 100644 index 00000000..491a80a9 Binary files /dev/null and b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll differ diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll.meta new file mode 100644 index 00000000..69e5f691 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Other/System.Runtime.CompilerServices.Unsafe.dll.meta @@ -0,0 +1,35 @@ +fileFormatVersion: 2 +guid: bd2b66cfee2b94dea92a1ff0385fa0cb +labels: +- NuGetForUnity +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net.meta new file mode 100644 index 00000000..d7e5543b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a612f894ce7024629851208a425b70cc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BclHelpers.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BclHelpers.cs new file mode 100644 index 00000000..bcff9a4e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BclHelpers.cs @@ -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 + } + + /// + /// Provides support for common .NET types that do not have a direct representation + /// in protobuf, using the definitions from bcl.proto + /// + public static class BclHelpers + { + /// + /// Creates a new instance of the specified type, bypassing the constructor. + /// + /// The type to create + /// The new instance + /// If the platform does not support constructor-skipping + 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 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)method.CreateDelegate(typeof(Func)); + } + } + 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) + }; + + /// + /// The default value for dates that are following google.protobuf.Timestamp semantics + /// + private static readonly DateTime TimestampEpoch = EpochOrigin[(int)DateTimeKind.Utc]; + + /// + /// Writes a TimeSpan to a protobuf stream using protobuf-net's own representation, bcl.TimeSpan + /// + 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()); + } + } + + /// + /// Parses a TimeSpan from a protobuf stream using protobuf-net's own representation, bcl.TimeSpan + /// + 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); + } + + /// + /// Parses a TimeSpan from a protobuf stream using the standardized format, google.protobuf.Duration + /// + 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); + } + + /// + /// Writes a TimeSpan to a protobuf stream using the standardized format, google.protobuf.Duration + /// + 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); + } + + /// + /// Parses a DateTime from a protobuf stream using the standardized format, google.protobuf.Timestamp + /// + 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); + } + + /// + /// Writes a DateTime to a protobuf stream using the standardized format, google.protobuf.Timestamp + /// + 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; + } + + /// + /// Parses a DateTime from a protobuf stream + /// + 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); + } + + /// + /// Writes a DateTime to a protobuf stream, excluding the Kind + /// + public static void WriteDateTime(DateTime value, ProtoWriter dest) + { + WriteDateTimeImpl(value, dest, false); + } + + /// + /// Writes a DateTime to a protobuf stream, including the Kind + /// + 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; + + /// + /// Parses a decimal from a protobuf stream + /// + 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); + } + + /// + /// Writes a decimal to a protobuf stream + /// + 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; + /// + /// Writes a Guid to a protobuf stream + /// + 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); + } + /// + /// Parses a Guid from a protobuf stream + /// + 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; + + /// + /// Optional behaviours that introduce .NET-specific functionality + /// + [Flags] + public enum NetObjectOptions : byte + { + /// + /// No special behaviour + /// + None = 0, + /// + /// Enables full object-tracking/full-graph support. + /// + AsReference = 1, + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance. + /// + DynamicType = 2, + /// + /// If false, the constructor for the type is bypassed during deserialization, meaning any field initializers + /// or other initialization code is skipped. + /// + UseConstructor = 4, + /// + /// Should the object index be reserved, rather than creating an object promptly + /// + LateSet = 8 + } + + /// + /// Reads an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc. + /// + 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; + } + + /// + /// Writes an *implementation specific* bundled .NET object, including (as options) type-metadata, identity/re-use, etc. + /// + 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); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BclHelpers.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BclHelpers.cs.meta new file mode 100644 index 00000000..da3a37a7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BclHelpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5072fbed211eb9f43a3cd2805dd75ef7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferExtension.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferExtension.cs new file mode 100644 index 00000000..ea428dd9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferExtension.cs @@ -0,0 +1,78 @@ +using System; +using System.IO; + +namespace ProtoBuf +{ + /// + /// Provides a simple buffer-based implementation of an extension object. + /// + 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 + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferExtension.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferExtension.cs.meta new file mode 100644 index 00000000..4a395911 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a9cf66041a027e94892d5014c2b905b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferPool.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferPool.cs new file mode 100644 index 00000000..8ad3d1ab --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferPool.cs @@ -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; + } + } + + /// + /// https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element + /// + 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); + } + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferPool.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferPool.cs.meta new file mode 100644 index 00000000..2870b8c7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/BufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 423b228ed060b91458bc6d4e6aa0f570 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/CallbackAttributes.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/CallbackAttributes.cs new file mode 100644 index 00000000..1adb8e5a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/CallbackAttributes.cs @@ -0,0 +1,33 @@ +using System; +using System.ComponentModel; + +namespace ProtoBuf +{ + /// Specifies a method on the root-contract in an hierarchy to be invoked before serialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoBeforeSerializationAttribute : Attribute { } + + /// Specifies a method on the root-contract in an hierarchy to be invoked after serialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoAfterSerializationAttribute : Attribute { } + + /// Specifies a method on the root-contract in an hierarchy to be invoked before deserialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoBeforeDeserializationAttribute : Attribute { } + + /// Specifies a method on the root-contract in an hierarchy to be invoked after deserialization. + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] +#if !CF && !PORTABLE && !COREFX && !PROFILE259 + [ImmutableObject(true)] +#endif + public sealed class ProtoAfterDeserializationAttribute : Attribute { } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/CallbackAttributes.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/CallbackAttributes.cs.meta new file mode 100644 index 00000000..7cf81a42 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/CallbackAttributes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 53de2cb3784c9dd43aa6f30d7df072a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler.meta new file mode 100644 index 00000000..9de78a67 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2cdd9eb2afa3ed24480a6035f507aad4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerContext.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerContext.cs new file mode 100644 index 00000000..6100200e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerContext.cs @@ -0,0 +1,1435 @@ +#if FEAT_COMPILER +//#define DEBUG_COMPILE +using System; +using System.Threading; +using ProtoBuf.Meta; +using ProtoBuf.Serializers; +using System.Reflection; +using System.Reflection.Emit; + +namespace ProtoBuf.Compiler +{ + internal readonly struct CodeLabel + { + public readonly Label Value; + public readonly int Index; + public CodeLabel(Label value, int index) + { + this.Value = value; + this.Index = index; + } + } + internal sealed class CompilerContext + { + public TypeModel Model => model; + + readonly DynamicMethod method; + static int next; + + internal CodeLabel DefineLabel() + { + CodeLabel result = new CodeLabel(il.DefineLabel(), nextLabel++); + return result; + } +#if DEBUG_COMPILE + static readonly string traceCompilePath; + static CompilerContext() + { + traceCompilePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), + "TraceCompile.txt"); + Console.WriteLine("DEBUG_COMPILE enabled; writing to " + traceCompilePath); + } +#endif + [System.Diagnostics.Conditional("DEBUG_COMPILE")] + private void TraceCompile(string value) + { +#if DEBUG_COMPILE + if (!string.IsNullOrWhiteSpace(value)) + { + using (System.IO.StreamWriter sw = System.IO.File.AppendText(traceCompilePath)) + { + sw.WriteLine(value); + } + } +#endif + } + internal void MarkLabel(CodeLabel label) + { + il.MarkLabel(label.Value); + TraceCompile("#: " + label.Index); + } + + public static ProtoSerializer BuildSerializer(IProtoSerializer head, TypeModel model) + { + Type type = head.ExpectedType; + try + { + CompilerContext ctx = new CompilerContext(type, true, true, model, typeof(object)); + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(type); + ctx.WriteNullCheckedTail(type, head, null); + ctx.Emit(OpCodes.Ret); + return (ProtoSerializer)ctx.method.CreateDelegate( + typeof(ProtoSerializer)); + } + catch (Exception ex) + { + string name = type.FullName; + if (string.IsNullOrEmpty(name)) name = type.Name; + throw new InvalidOperationException("It was not possible to prepare a serializer for: " + name, ex); + } + } + /*public static ProtoCallback BuildCallback(IProtoTypeSerializer head) + { + Type type = head.ExpectedType; + CompilerContext ctx = new CompilerContext(type, true, true); + using (Local typedVal = new Local(ctx, type)) + { + ctx.LoadValue(Local.InputValue); + ctx.CastFromObject(type); + ctx.StoreValue(typedVal); + CodeLabel[] jumpTable = new CodeLabel[4]; + for(int i = 0 ; i < jumpTable.Length ; i++) { + jumpTable[i] = ctx.DefineLabel(); + } + ctx.LoadReaderWriter(); + ctx.Switch(jumpTable); + ctx.Return(); + for(int i = 0 ; i < jumpTable.Length ; i++) { + ctx.MarkLabel(jumpTable[i]); + if (head.HasCallbacks((TypeModel.CallbackType)i)) + { + head.EmitCallback(ctx, typedVal, (TypeModel.CallbackType)i); + } + ctx.Return(); + } + } + + ctx.Emit(OpCodes.Ret); + return (ProtoCallback)ctx.method.CreateDelegate( + typeof(ProtoCallback)); + }*/ + public static ProtoDeserializer BuildDeserializer(IProtoSerializer head, TypeModel model) + { + Type type = head.ExpectedType; + CompilerContext ctx = new CompilerContext(type, false, true, model, typeof(object)); + + using (Local typedVal = new Local(ctx, type)) + { + if (!Helpers.IsValueType(type)) + { + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(type); + ctx.StoreValue(typedVal); + } + else + { + ctx.LoadValue(ctx.InputValue); + CodeLabel notNull = ctx.DefineLabel(), endNull = ctx.DefineLabel(); + ctx.BranchIfTrue(notNull, true); + + ctx.LoadAddress(typedVal, type); + ctx.EmitCtor(type); + ctx.Branch(endNull, true); + + ctx.MarkLabel(notNull); + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(type); + ctx.StoreValue(typedVal); + + ctx.MarkLabel(endNull); + } + head.EmitRead(ctx, typedVal); + + if (head.ReturnsValue) + { + ctx.StoreValue(typedVal); + } + + ctx.LoadValue(typedVal); + ctx.CastToObject(type); + } + ctx.Emit(OpCodes.Ret); + return (ProtoDeserializer)ctx.method.CreateDelegate( + typeof(ProtoDeserializer)); + } + + internal void Return() + { + Emit(OpCodes.Ret); + } + + static bool IsObject(Type type) + { + return type == typeof(object); + } + + internal void CastToObject(Type type) + { + if (IsObject(type)) + { } + else if (Helpers.IsValueType(type)) + { + il.Emit(OpCodes.Box, type); + TraceCompile(OpCodes.Box + ": " + type); + } + else + { + il.Emit(OpCodes.Castclass, MapType(typeof(object))); + TraceCompile(OpCodes.Castclass + ": " + type); + } + } + + internal void CastFromObject(Type type) + { + if (IsObject(type)) + { } + else if (Helpers.IsValueType(type)) + { + switch (MetadataVersion) + { + case ILVersion.Net1: + il.Emit(OpCodes.Unbox, type); + il.Emit(OpCodes.Ldobj, type); + TraceCompile(OpCodes.Unbox + ": " + type); + TraceCompile(OpCodes.Ldobj + ": " + type); + break; + default: + + il.Emit(OpCodes.Unbox_Any, type); + TraceCompile(OpCodes.Unbox_Any + ": " + type); + break; + } + } + else + { + il.Emit(OpCodes.Castclass, type); + TraceCompile(OpCodes.Castclass + ": " + type); + } + } + private readonly bool isStatic; + private readonly RuntimeTypeModel.SerializerPair[] methodPairs; + + internal MethodBuilder GetDedicatedMethod(int metaKey, bool read) + { + if (methodPairs == null) return null; + // but if we *do* have pairs, we demand that we find a match... + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == metaKey) { return read ? methodPairs[i].Deserialize : methodPairs[i].Serialize; } + } + throw new ArgumentException("Meta-key not found", "metaKey"); + } + + internal int MapMetaKeyToCompiledKey(int metaKey) + { + if (metaKey < 0 || methodPairs == null) return metaKey; // all meta, or a dummy/wildcard key + + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == metaKey) return i; + } + throw new ArgumentException("Key could not be mapped: " + metaKey.ToString(), "metaKey"); + } + + + private readonly bool isWriter; + + private readonly bool nonPublic; + internal bool NonPublic { get { return nonPublic; } } + + private readonly Local inputValue; + public Local InputValue { get { return inputValue; } } + + private readonly string assemblyName; + internal CompilerContext(ILGenerator il, bool isStatic, bool isWriter, RuntimeTypeModel.SerializerPair[] methodPairs, TypeModel model, ILVersion metadataVersion, string assemblyName, Type inputType, string traceName) + { + if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException(nameof(assemblyName)); + this.assemblyName = assemblyName; + this.isStatic = isStatic; + this.methodPairs = methodPairs ?? throw new ArgumentNullException(nameof(methodPairs)); + this.il = il ?? throw new ArgumentNullException(nameof(il)); + // nonPublic = false; <== implicit + this.isWriter = isWriter; + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.metadataVersion = metadataVersion; + if (inputType != null) this.inputValue = new Local(null, inputType); + TraceCompile(">> " + traceName); + } + + private CompilerContext(Type associatedType, bool isWriter, bool isStatic, TypeModel model, Type inputType) + { + metadataVersion = ILVersion.Net2; + this.isStatic = isStatic; + this.isWriter = isWriter; + this.model = model ?? throw new ArgumentNullException(nameof(model)); + nonPublic = true; + Type[] paramTypes; + Type returnType; + if (isWriter) + { + returnType = typeof(void); + paramTypes = new Type[] { typeof(object), typeof(ProtoWriter) }; + } + else + { + returnType = typeof(object); + paramTypes = new Type[] { typeof(object), typeof(ProtoReader) }; + } + int uniqueIdentifier; +#if PLAT_NO_INTERLOCKED + uniqueIdentifier = ++next; +#else + uniqueIdentifier = Interlocked.Increment(ref next); +#endif + method = new DynamicMethod("proto_" + uniqueIdentifier.ToString(), returnType, paramTypes, associatedType +#if COREFX + .GetTypeInfo() +#endif + .IsInterface ? typeof(object) : associatedType, true); + this.il = method.GetILGenerator(); + if (inputType != null) this.inputValue = new Local(null, inputType); + TraceCompile(">> " + method.Name); + } + + private readonly ILGenerator il; + + private void Emit(OpCode opcode) + { + il.Emit(opcode); + TraceCompile(opcode.ToString()); + } + + public void LoadValue(string value) + { + if (value == null) + { + LoadNullRef(); + } + else + { + il.Emit(OpCodes.Ldstr, value); + TraceCompile(OpCodes.Ldstr + ": " + value); + } + } + + public void LoadValue(float value) + { + il.Emit(OpCodes.Ldc_R4, value); + TraceCompile(OpCodes.Ldc_R4 + ": " + value); + } + + public void LoadValue(double value) + { + il.Emit(OpCodes.Ldc_R8, value); + TraceCompile(OpCodes.Ldc_R8 + ": " + value); + } + + public void LoadValue(long value) + { + il.Emit(OpCodes.Ldc_I8, value); + TraceCompile(OpCodes.Ldc_I8 + ": " + value); + } + + public void LoadValue(int value) + { + switch (value) + { + case 0: Emit(OpCodes.Ldc_I4_0); break; + case 1: Emit(OpCodes.Ldc_I4_1); break; + case 2: Emit(OpCodes.Ldc_I4_2); break; + case 3: Emit(OpCodes.Ldc_I4_3); break; + case 4: Emit(OpCodes.Ldc_I4_4); break; + case 5: Emit(OpCodes.Ldc_I4_5); break; + case 6: Emit(OpCodes.Ldc_I4_6); break; + case 7: Emit(OpCodes.Ldc_I4_7); break; + case 8: Emit(OpCodes.Ldc_I4_8); break; + case -1: Emit(OpCodes.Ldc_I4_M1); break; + default: + if (value >= -128 && value <= 127) + { + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + TraceCompile(OpCodes.Ldc_I4_S + ": " + value); + } + else + { + il.Emit(OpCodes.Ldc_I4, value); + TraceCompile(OpCodes.Ldc_I4 + ": " + value); + } + break; + + } + } + + MutableList locals = new MutableList(); + internal LocalBuilder GetFromPool(Type type) + { + int count = locals.Count; + for (int i = 0; i < count; i++) + { + LocalBuilder item = (LocalBuilder)locals[i]; + if (item != null && item.LocalType == type) + { + locals[i] = null; // remove from pool + return item; + } + } + LocalBuilder result = il.DeclareLocal(type); + TraceCompile("$ " + result + ": " + type); + return result; + } + + // + internal void ReleaseToPool(LocalBuilder value) + { + int count = locals.Count; + for (int i = 0; i < count; i++) + { + if (locals[i] == null) + { + locals[i] = value; // released into existing slot + return; + } + } + locals.Add(value); // create a new slot + } + + public void LoadReaderWriter() + { + Emit(isStatic ? OpCodes.Ldarg_1 : OpCodes.Ldarg_2); + } + + public void StoreValue(Local local) + { + if (local == this.InputValue) + { + byte b = isStatic ? (byte)0 : (byte)1; + il.Emit(OpCodes.Starg_S, b); + TraceCompile(OpCodes.Starg_S + ": $" + b); + } + else + { + + switch (local.Value.LocalIndex) + { + case 0: Emit(OpCodes.Stloc_0); break; + case 1: Emit(OpCodes.Stloc_1); break; + case 2: Emit(OpCodes.Stloc_2); break; + case 3: Emit(OpCodes.Stloc_3); break; + default: + + OpCode code = UseShortForm(local) ? OpCodes.Stloc_S : OpCodes.Stloc; + il.Emit(code, local.Value); + TraceCompile(code + ": $" + local.Value); + + break; + } + } + } + + public void LoadValue(Local local) + { + if (local == null) { /* nothing to do; top of stack */} + else if (local == this.InputValue) + { + Emit(isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1); + } + else + { + + switch (local.Value.LocalIndex) + { + case 0: Emit(OpCodes.Ldloc_0); break; + case 1: Emit(OpCodes.Ldloc_1); break; + case 2: Emit(OpCodes.Ldloc_2); break; + case 3: Emit(OpCodes.Ldloc_3); break; + default: + + OpCode code = UseShortForm(local) ? OpCodes.Ldloc_S : OpCodes.Ldloc; + il.Emit(code, local.Value); + TraceCompile(code + ": $" + local.Value); + + break; + } + } + } + + public Local GetLocalWithValue(Type type, Compiler.Local fromValue) + { + if (fromValue != null) + { + if (fromValue.Type == type) return fromValue.AsCopy(); + // otherwise, load onto the stack and let the default handling (below) deal with it + LoadValue(fromValue); + if (!Helpers.IsValueType(type) && (fromValue.Type == null || !type.IsAssignableFrom(fromValue.Type))) + { // need to cast + Cast(type); + } + } + // need to store the value from the stack + Local result = new Local(this, type); + StoreValue(result); + return result; + } + + internal void EmitBasicRead(string methodName, Type expectedType) + { + MethodInfo method = MapType(typeof(ProtoReader)).GetMethod( + methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + if (method == null || method.ReturnType != expectedType + || method.GetParameters().Length != 0) throw new ArgumentException("methodName"); + LoadReaderWriter(); + EmitCall(method); + } + + internal void EmitBasicRead(Type helperType, string methodName, Type expectedType) + { + MethodInfo method = helperType.GetMethod( + methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + if (method == null || method.ReturnType != expectedType + || method.GetParameters().Length != 1) throw new ArgumentException("methodName"); + LoadReaderWriter(); + EmitCall(method); + } + + internal void EmitBasicWrite(string methodName, Compiler.Local fromValue) + { + if (string.IsNullOrEmpty(methodName)) throw new ArgumentNullException("methodName"); + LoadValue(fromValue); + LoadReaderWriter(); + EmitCall(GetWriterMethod(methodName)); + } + + private MethodInfo GetWriterMethod(string methodName) + { + Type writerType = MapType(typeof(ProtoWriter)); + MethodInfo[] methods = writerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + foreach (MethodInfo method in methods) + { + if (method.Name != methodName) continue; + ParameterInfo[] pis = method.GetParameters(); + if (pis.Length == 2 && pis[1].ParameterType == writerType) return method; + } + throw new ArgumentException("No suitable method found for: " + methodName, "methodName"); + } + + internal void EmitWrite(Type helperType, string methodName, Compiler.Local valueFrom) + { + if (string.IsNullOrEmpty(methodName)) throw new ArgumentNullException("methodName"); + MethodInfo method = helperType.GetMethod( + methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + if (method == null || method.ReturnType != MapType(typeof(void))) throw new ArgumentException("methodName"); + LoadValue(valueFrom); + LoadReaderWriter(); + EmitCall(method); + } + + public void EmitCall(MethodInfo method) { EmitCall(method, null); } + + public void EmitCall(MethodInfo method, Type targetType) + { + Helpers.DebugAssert(method != null); + MemberInfo member = method; + CheckAccessibility(ref member); + OpCode opcode; + if (method.IsStatic || Helpers.IsValueType(method.DeclaringType)) + { + opcode = OpCodes.Call; + } + else + { + opcode = OpCodes.Callvirt; + if (targetType != null && Helpers.IsValueType(targetType) && !Helpers.IsValueType(method.DeclaringType)) + { + Constrain(targetType); + } + } + il.EmitCall(opcode, method, null); + TraceCompile(opcode + ": " + method + " on " + method.DeclaringType + (targetType == null ? "" : (" via " + targetType))); + } + + /// + /// Pushes a null reference onto the stack. Note that this should only + /// be used to return a null (or set a variable to null); for null-tests + /// use BranchIfTrue / BranchIfFalse. + /// + public void LoadNullRef() + { + Emit(OpCodes.Ldnull); + } + + private int nextLabel; + + internal void WriteNullCheckedTail(Type type, IProtoSerializer tail, Compiler.Local valueFrom) + { + if (Helpers.IsValueType(type)) + { + Type underlyingType = Helpers.GetUnderlyingType(type); + + if (underlyingType == null) + { // not a nullable T; can invoke directly + tail.EmitWrite(this, valueFrom); + } + else + { // nullable T; check HasValue + using (Compiler.Local valOrNull = GetLocalWithValue(type, valueFrom)) + { + LoadAddress(valOrNull, type); + LoadValue(type.GetProperty("HasValue")); + CodeLabel @end = DefineLabel(); + BranchIfFalse(@end, false); + LoadAddress(valOrNull, type); + EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + tail.EmitWrite(this, null); + MarkLabel(@end); + } + } + } + else + { // ref-type; do a null-check + LoadValue(valueFrom); + CopyValue(); + CodeLabel hasVal = DefineLabel(), @end = DefineLabel(); + BranchIfTrue(hasVal, true); + DiscardValue(); + Branch(@end, false); + MarkLabel(hasVal); + tail.EmitWrite(this, null); + MarkLabel(@end); + } + } + + internal void ReadNullCheckedTail(Type type, IProtoSerializer tail, Compiler.Local valueFrom) + { + + Type underlyingType; + + if (Helpers.IsValueType(type) && (underlyingType = Helpers.GetUnderlyingType(type)) != null) + { + if (tail.RequiresOldValue) + { + // we expect the input value to be in valueFrom; need to unpack it from T? + using (Local loc = GetLocalWithValue(type, valueFrom)) + { + LoadAddress(loc, type); + EmitCall(type.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + } + else + { + Helpers.DebugAssert(valueFrom == null); // not expecting a valueFrom in this case + } + tail.EmitRead(this, null); // either unwrapped on the stack or not provided + if (tail.ReturnsValue) + { + // now re-wrap the value + EmitCtor(type, underlyingType); + } + return; + } + + // either a ref-type of a non-nullable struct; treat "as is", even if null + // (the type-serializer will handle the null case; it needs to allow null + // inputs to perform the correct type of subclass creation) + tail.EmitRead(this, valueFrom); + } + + public void EmitCtor(Type type) + { + EmitCtor(type, Helpers.EmptyTypes); + } + + public void EmitCtor(ConstructorInfo ctor) + { + if (ctor == null) throw new ArgumentNullException("ctor"); + MemberInfo ctorMember = ctor; + CheckAccessibility(ref ctorMember); + il.Emit(OpCodes.Newobj, ctor); + TraceCompile(OpCodes.Newobj + ": " + ctor.DeclaringType); + } + + public void InitLocal(Type type, Compiler.Local target) + { + LoadAddress(target, type, evenIfClass: true); // for class, initobj is a load-null, store-indirect + il.Emit(OpCodes.Initobj, type); + TraceCompile(OpCodes.Initobj + ": " + type); + } + + public void EmitCtor(Type type, params Type[] parameterTypes) + { + Helpers.DebugAssert(type != null); + Helpers.DebugAssert(parameterTypes != null); + if (Helpers.IsValueType(type) && parameterTypes.Length == 0) + { + il.Emit(OpCodes.Initobj, type); + TraceCompile(OpCodes.Initobj + ": " + type); + } + else + { + ConstructorInfo ctor = Helpers.GetConstructor(type +#if COREFX + .GetTypeInfo() +#endif + , parameterTypes, true); + if (ctor == null) throw new InvalidOperationException("No suitable constructor found for " + type.FullName); + EmitCtor(ctor); + } + } + + BasicList knownTrustedAssemblies, knownUntrustedAssemblies; + + bool InternalsVisible(Assembly assembly) + { + if (string.IsNullOrEmpty(assemblyName)) return false; + if (knownTrustedAssemblies != null) + { + if (knownTrustedAssemblies.IndexOfReference(assembly) >= 0) + { + return true; + } + } + if (knownUntrustedAssemblies != null) + { + if (knownUntrustedAssemblies.IndexOfReference(assembly) >= 0) + { + return false; + } + } + bool isTrusted = false; + Type attributeType = MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute)); + if (attributeType == null) return false; + +#if COREFX + foreach (System.Runtime.CompilerServices.InternalsVisibleToAttribute attrib in assembly.GetCustomAttributes(attributeType)) +#else + foreach (System.Runtime.CompilerServices.InternalsVisibleToAttribute attrib in assembly.GetCustomAttributes(attributeType, false)) +#endif + { + if (attrib.AssemblyName == assemblyName || attrib.AssemblyName.StartsWith(assemblyName + ",")) + { + isTrusted = true; + break; + } + } + + if (isTrusted) + { + if (knownTrustedAssemblies == null) knownTrustedAssemblies = new BasicList(); + knownTrustedAssemblies.Add(assembly); + } + else + { + if (knownUntrustedAssemblies == null) knownUntrustedAssemblies = new BasicList(); + knownUntrustedAssemblies.Add(assembly); + } + return isTrusted; + } + + internal void CheckAccessibility(ref MemberInfo member) + { + if (member == null) + { + throw new ArgumentNullException(nameof(member)); + } +#if !COREFX + Type type; +#endif + if (!NonPublic) + { + if (member is FieldInfo && member.Name.StartsWith("<") & member.Name.EndsWith(">k__BackingField")) + { + var propName = member.Name.Substring(1, member.Name.Length - 17); + var prop = member.DeclaringType.GetProperty(propName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + if (prop != null) member = prop; + } + bool isPublic; +#if COREFX + if (member is TypeInfo) + { + TypeInfo ti = (TypeInfo)member; + do + { + isPublic = ti.IsNestedPublic || ti.IsPublic || ((ti.IsNested || ti.IsNestedAssembly || ti.IsNestedFamORAssem) && InternalsVisible(ti.Assembly)); + } while (isPublic && ti.IsNested && (ti = ti.DeclaringType.GetTypeInfo()) != null); + } + else if (member is FieldInfo) + { + FieldInfo field = ((FieldInfo)member); + isPublic = field.IsPublic || ((field.IsAssembly || field.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(field.DeclaringType))); + } + else if (member is PropertyInfo) + { + isPublic = true; // defer to get/set + } + else if (member is ConstructorInfo) + { + ConstructorInfo ctor = ((ConstructorInfo)member); + isPublic = ctor.IsPublic || ((ctor.IsAssembly || ctor.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(ctor.DeclaringType))); + } + else if (member is MethodInfo) + { + MethodInfo method = ((MethodInfo)member); + isPublic = method.IsPublic || ((method.IsAssembly || method.IsFamilyOrAssembly) && InternalsVisible(Helpers.GetAssembly(method.DeclaringType))); + if (!isPublic) + { + // allow calls to TypeModel protected methods, and methods we are in the process of creating + if ( + member is MethodBuilder || + member.DeclaringType == MapType(typeof(TypeModel))) + isPublic = true; + } + } + else + { + throw new NotSupportedException(member.GetType().Name); + } +#else + MemberTypes memberType = member.MemberType; + switch (memberType) + { + case MemberTypes.TypeInfo: + // top-level type + type = (Type)member; + isPublic = type.IsPublic || InternalsVisible(type.Assembly); + break; + case MemberTypes.NestedType: + type = (Type)member; + do + { + isPublic = type.IsNestedPublic || type.IsPublic || ((type.DeclaringType == null || type.IsNestedAssembly || type.IsNestedFamORAssem) && InternalsVisible(type.Assembly)); + } while (isPublic && (type = type.DeclaringType) != null); // ^^^ !type.IsNested, but not all runtimes have that + break; + case MemberTypes.Field: + FieldInfo field = ((FieldInfo)member); + isPublic = field.IsPublic || ((field.IsAssembly || field.IsFamilyOrAssembly) && InternalsVisible(field.DeclaringType.Assembly)); + break; + case MemberTypes.Constructor: + ConstructorInfo ctor = ((ConstructorInfo)member); + isPublic = ctor.IsPublic || ((ctor.IsAssembly || ctor.IsFamilyOrAssembly) && InternalsVisible(ctor.DeclaringType.Assembly)); + break; + case MemberTypes.Method: + MethodInfo method = ((MethodInfo)member); + isPublic = method.IsPublic || ((method.IsAssembly || method.IsFamilyOrAssembly) && InternalsVisible(method.DeclaringType.Assembly)); + if (!isPublic) + { + // allow calls to TypeModel protected methods, and methods we are in the process of creating + if ( + member is MethodBuilder || + member.DeclaringType == MapType(typeof(TypeModel))) isPublic = true; + } + break; + case MemberTypes.Property: + isPublic = true; // defer to get/set + break; + default: + throw new NotSupportedException(memberType.ToString()); + } +#endif + if (!isPublic) + { +#if COREFX + if (member is TypeInfo) + { + throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " + + ((TypeInfo)member).FullName); + } + else + { + throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " + + member.DeclaringType.FullName + "." + member.Name); + } + +#else + switch (memberType) + { + case MemberTypes.TypeInfo: + case MemberTypes.NestedType: + throw new InvalidOperationException("Non-public type cannot be used with full dll compilation: " + + ((Type)member).FullName); + default: + throw new InvalidOperationException("Non-public member cannot be used with full dll compilation: " + + member.DeclaringType.FullName + "." + member.Name); + } +#endif + + } + } + } + + public void LoadValue(FieldInfo field) + { + MemberInfo member = field; + CheckAccessibility(ref member); + if (member is PropertyInfo) + { + LoadValue((PropertyInfo)member); + } + else + { + OpCode code = field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld; + il.Emit(code, field); + TraceCompile(code + ": " + field + " on " + field.DeclaringType); + } + } + + public void StoreValue(FieldInfo field) + { + MemberInfo member = field; + CheckAccessibility(ref member); + if (member is PropertyInfo) + { + StoreValue((PropertyInfo)member); + } + else + { + OpCode code = field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld; + il.Emit(code, field); + TraceCompile(code + ": " + field + " on " + field.DeclaringType); + } + } + + public void LoadValue(PropertyInfo property) + { + MemberInfo member = property; + CheckAccessibility(ref member); + EmitCall(Helpers.GetGetMethod(property, true, true)); + } + + public void StoreValue(PropertyInfo property) + { + MemberInfo member = property; + CheckAccessibility(ref member); + EmitCall(Helpers.GetSetMethod(property, true, true)); + } + + //internal void EmitInstance() + //{ + // if (isStatic) throw new InvalidOperationException(); + // Emit(OpCodes.Ldarg_0); + //} + + internal static void LoadValue(ILGenerator il, int value) + { + switch (value) + { + case 0: il.Emit(OpCodes.Ldc_I4_0); break; + case 1: il.Emit(OpCodes.Ldc_I4_1); break; + case 2: il.Emit(OpCodes.Ldc_I4_2); break; + case 3: il.Emit(OpCodes.Ldc_I4_3); break; + case 4: il.Emit(OpCodes.Ldc_I4_4); break; + case 5: il.Emit(OpCodes.Ldc_I4_5); break; + case 6: il.Emit(OpCodes.Ldc_I4_6); break; + case 7: il.Emit(OpCodes.Ldc_I4_7); break; + case 8: il.Emit(OpCodes.Ldc_I4_8); break; + case -1: il.Emit(OpCodes.Ldc_I4_M1); break; + default: il.Emit(OpCodes.Ldc_I4, value); break; + } + } + + private bool UseShortForm(Local local) + { + return local.Value.LocalIndex < 256; + } + + internal void LoadAddress(Local local, Type type, bool evenIfClass = false) + { + if (evenIfClass || Helpers.IsValueType(type)) + { + if (local == null) + { + throw new InvalidOperationException("Cannot load the address of the head of the stack"); + } + + if (local == this.InputValue) + { + il.Emit(OpCodes.Ldarga_S, (isStatic ? (byte)0 : (byte)1)); + TraceCompile(OpCodes.Ldarga_S + ": $" + (isStatic ? 0 : 1)); + } + else + { + OpCode code = UseShortForm(local) ? OpCodes.Ldloca_S : OpCodes.Ldloca; + il.Emit(code, local.Value); + TraceCompile(code + ": $" + local.Value); + } + + } + else + { // reference-type; already *is* the address; just load it + LoadValue(local); + } + } + + internal void Branch(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Br_S : OpCodes.Br; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfFalse(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Brfalse_S : OpCodes.Brfalse; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfTrue(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Brtrue_S : OpCodes.Brtrue; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfEqual(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Beq_S : OpCodes.Beq; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + //internal void TestEqual() + //{ + // Emit(OpCodes.Ceq); + //} + + internal void CopyValue() + { + Emit(OpCodes.Dup); + } + + internal void BranchIfGreater(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Bgt_S : OpCodes.Bgt; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void BranchIfLess(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Blt_S : OpCodes.Blt; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal void DiscardValue() + { + Emit(OpCodes.Pop); + } + + public void Subtract() + { + Emit(OpCodes.Sub); + } + + public void Switch(CodeLabel[] jumpTable) + { + const int MAX_JUMPS = 128; + + if (jumpTable.Length <= MAX_JUMPS) + { + // simple case + Label[] labels = new Label[jumpTable.Length]; + for (int i = 0; i < labels.Length; i++) + { + labels[i] = jumpTable[i].Value; + } + TraceCompile(OpCodes.Switch.ToString()); + il.Emit(OpCodes.Switch, labels); + } + else + { + // too many to jump easily (especially on Android) - need to split up (note: uses a local pulled from the stack) + using (Local val = GetLocalWithValue(MapType(typeof(int)), null)) + { + int count = jumpTable.Length, offset = 0; + int blockCount = count / MAX_JUMPS; + if ((count % MAX_JUMPS) != 0) blockCount++; + + Label[] blockLabels = new Label[blockCount]; + for (int i = 0; i < blockCount; i++) + { + blockLabels[i] = il.DefineLabel(); + } + CodeLabel endOfSwitch = DefineLabel(); + + LoadValue(val); + LoadValue(MAX_JUMPS); + Emit(OpCodes.Div); + TraceCompile(OpCodes.Switch.ToString()); + il.Emit(OpCodes.Switch, blockLabels); + Branch(endOfSwitch, false); + + Label[] innerLabels = new Label[MAX_JUMPS]; + for (int blockIndex = 0; blockIndex < blockCount; blockIndex++) + { + il.MarkLabel(blockLabels[blockIndex]); + + int itemsThisBlock = Math.Min(MAX_JUMPS, count); + count -= itemsThisBlock; + if (innerLabels.Length != itemsThisBlock) innerLabels = new Label[itemsThisBlock]; + + int subtract = offset; + for (int j = 0; j < itemsThisBlock; j++) + { + innerLabels[j] = jumpTable[offset++].Value; + } + LoadValue(val); + if (subtract != 0) // switches are always zero-based + { + LoadValue(subtract); + Emit(OpCodes.Sub); + } + TraceCompile(OpCodes.Switch.ToString()); + il.Emit(OpCodes.Switch, innerLabels); + if (count != 0) + { // force default to the very bottom + Branch(endOfSwitch, false); + } + } + Helpers.DebugAssert(count == 0, "Should use exactly all switch items"); + MarkLabel(endOfSwitch); + } + } + } + + internal void EndFinally() + { + il.EndExceptionBlock(); + TraceCompile("EndExceptionBlock"); + } + + internal void BeginFinally() + { + il.BeginFinallyBlock(); + TraceCompile("BeginFinallyBlock"); + } + + internal void EndTry(CodeLabel label, bool @short) + { + OpCode code = @short ? OpCodes.Leave_S : OpCodes.Leave; + il.Emit(code, label.Value); + TraceCompile(code + ": " + label.Index); + } + + internal CodeLabel BeginTry() + { + CodeLabel label = new CodeLabel(il.BeginExceptionBlock(), nextLabel++); + TraceCompile("BeginExceptionBlock: " + label.Index); + return label; + } + + internal void Constrain(Type type) + { + il.Emit(OpCodes.Constrained, type); + TraceCompile(OpCodes.Constrained + ": " + type); + } + + internal void TryCast(Type type) + { + il.Emit(OpCodes.Isinst, type); + TraceCompile(OpCodes.Isinst + ": " + type); + } + + internal void Cast(Type type) + { + il.Emit(OpCodes.Castclass, type); + TraceCompile(OpCodes.Castclass + ": " + type); + } + + public IDisposable Using(Local local) + { + return new UsingBlock(this, local); + } + + private sealed class UsingBlock : IDisposable + { + private Local local; + CompilerContext ctx; + CodeLabel label; + /// + /// Creates a new "using" block (equivalent) around a variable; + /// the variable must exist, and note that (unlike in C#) it is + /// the variables *final* value that gets disposed. If you need + /// *original* disposal, copy your variable first. + /// + /// It is the callers responsibility to ensure that the variable's + /// scope fully-encapsulates the "using"; if not, the variable + /// may be re-used (and thus re-assigned) unexpectedly. + /// + public UsingBlock(CompilerContext ctx, Local local) + { + if (ctx == null) throw new ArgumentNullException("ctx"); + if (local == null) throw new ArgumentNullException("local"); + + Type type = local.Type; + // check if **never** disposable + if ((Helpers.IsValueType(type) || Helpers.IsSealed(type)) && + !ctx.MapType(typeof(IDisposable)).IsAssignableFrom(type)) + { + return; // nothing to do! easiest "using" block ever + // (note that C# wouldn't allow this as a "using" block, + // but we'll be generous and simply not do anything) + } + this.local = local; + this.ctx = ctx; + label = ctx.BeginTry(); + + } + public void Dispose() + { + if (local == null || ctx == null) return; + + ctx.EndTry(label, false); + ctx.BeginFinally(); + Type disposableType = ctx.MapType(typeof(IDisposable)); + MethodInfo dispose = disposableType.GetMethod("Dispose"); + Type type = local.Type; + // remember that we've already (in the .ctor) excluded the case + // where it *cannot* be disposable + if (Helpers.IsValueType(type)) + { + ctx.LoadAddress(local, type); + switch (ctx.MetadataVersion) + { + case ILVersion.Net1: + ctx.LoadValue(local); + ctx.CastToObject(type); + break; + default: + ctx.Constrain(type); + break; + } + ctx.EmitCall(dispose); + } + else + { + Compiler.CodeLabel @null = ctx.DefineLabel(); + if (disposableType.IsAssignableFrom(type)) + { // *known* to be IDisposable; just needs a null-check + ctx.LoadValue(local); + ctx.BranchIfFalse(@null, true); + ctx.LoadAddress(local, type); + } + else + { // *could* be IDisposable; test via "as" + using (Compiler.Local disp = new Compiler.Local(ctx, disposableType)) + { + ctx.LoadValue(local); + ctx.TryCast(disposableType); + ctx.CopyValue(); + ctx.StoreValue(disp); + ctx.BranchIfFalse(@null, true); + ctx.LoadAddress(disp, disposableType); + } + } + ctx.EmitCall(dispose); + ctx.MarkLabel(@null); + } + ctx.EndFinally(); + this.local = null; + this.ctx = null; + label = new CodeLabel(); // default + } + } + + internal void Add() + { + Emit(OpCodes.Add); + } + + internal void LoadLength(Local arr, bool zeroIfNull) + { + Helpers.DebugAssert(arr.Type.IsArray && arr.Type.GetArrayRank() == 1); + + if (zeroIfNull) + { + Compiler.CodeLabel notNull = DefineLabel(), done = DefineLabel(); + LoadValue(arr); + CopyValue(); // optimised for non-null case + BranchIfTrue(notNull, true); + DiscardValue(); + LoadValue(0); + Branch(done, true); + MarkLabel(notNull); + Emit(OpCodes.Ldlen); + Emit(OpCodes.Conv_I4); + MarkLabel(done); + } + else + { + LoadValue(arr); + Emit(OpCodes.Ldlen); + Emit(OpCodes.Conv_I4); + } + } + + internal void CreateArray(Type elementType, Local length) + { + LoadValue(length); + il.Emit(OpCodes.Newarr, elementType); + TraceCompile(OpCodes.Newarr + ": " + elementType); + } + + internal void LoadArrayValue(Local arr, Local i) + { + Type type = arr.Type; + Helpers.DebugAssert(type.IsArray && arr.Type.GetArrayRank() == 1); + type = type.GetElementType(); + Helpers.DebugAssert(type != null, "Not an array: " + arr.Type.FullName); + LoadValue(arr); + LoadValue(i); + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.SByte: Emit(OpCodes.Ldelem_I1); break; + case ProtoTypeCode.Int16: Emit(OpCodes.Ldelem_I2); break; + case ProtoTypeCode.Int32: Emit(OpCodes.Ldelem_I4); break; + case ProtoTypeCode.Int64: Emit(OpCodes.Ldelem_I8); break; + + case ProtoTypeCode.Byte: Emit(OpCodes.Ldelem_U1); break; + case ProtoTypeCode.UInt16: Emit(OpCodes.Ldelem_U2); break; + case ProtoTypeCode.UInt32: Emit(OpCodes.Ldelem_U4); break; + case ProtoTypeCode.UInt64: Emit(OpCodes.Ldelem_I8); break; // odd, but this is what C# does... + + case ProtoTypeCode.Single: Emit(OpCodes.Ldelem_R4); break; + case ProtoTypeCode.Double: Emit(OpCodes.Ldelem_R8); break; + default: + if (Helpers.IsValueType(type)) + { + il.Emit(OpCodes.Ldelema, type); + il.Emit(OpCodes.Ldobj, type); + TraceCompile(OpCodes.Ldelema + ": " + type); + TraceCompile(OpCodes.Ldobj + ": " + type); + } + else + { + Emit(OpCodes.Ldelem_Ref); + } + + break; + } + } + + internal void LoadValue(Type type) + { + il.Emit(OpCodes.Ldtoken, type); + TraceCompile(OpCodes.Ldtoken + ": " + type); + EmitCall(MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle")); + } + + internal void ConvertToInt32(ProtoTypeCode typeCode, bool uint32Overflow) + { + switch (typeCode) + { + case ProtoTypeCode.Byte: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.UInt16: + Emit(OpCodes.Conv_I4); + break; + case ProtoTypeCode.Int32: + break; + case ProtoTypeCode.Int64: + Emit(OpCodes.Conv_Ovf_I4); + break; + case ProtoTypeCode.UInt32: + Emit(uint32Overflow ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4); + break; + case ProtoTypeCode.UInt64: + Emit(OpCodes.Conv_Ovf_I4_Un); + break; + default: + throw new InvalidOperationException("ConvertToInt32 not implemented for: " + typeCode.ToString()); + } + } + + internal void ConvertFromInt32(ProtoTypeCode typeCode, bool uint32Overflow) + { + switch (typeCode) + { + case ProtoTypeCode.SByte: Emit(OpCodes.Conv_Ovf_I1); break; + case ProtoTypeCode.Byte: Emit(OpCodes.Conv_Ovf_U1); break; + case ProtoTypeCode.Int16: Emit(OpCodes.Conv_Ovf_I2); break; + case ProtoTypeCode.UInt16: Emit(OpCodes.Conv_Ovf_U2); break; + case ProtoTypeCode.Int32: break; + case ProtoTypeCode.UInt32: Emit(uint32Overflow ? OpCodes.Conv_Ovf_U4 : OpCodes.Conv_U4); break; + case ProtoTypeCode.Int64: Emit(OpCodes.Conv_I8); break; + case ProtoTypeCode.UInt64: Emit(OpCodes.Conv_U8); break; + default: throw new InvalidOperationException(); + } + } + + internal void LoadValue(decimal value) + { + if (value == 0M) + { + LoadValue(typeof(decimal).GetField("Zero")); + } + else + { + int[] bits = decimal.GetBits(value); + LoadValue(bits[0]); // lo + LoadValue(bits[1]); // mid + LoadValue(bits[2]); // hi + LoadValue((int)(((uint)bits[3]) >> 31)); // isNegative (bool, but int for CLI purposes) + LoadValue((bits[3] >> 16) & 0xFF); // scale (byte, but int for CLI purposes) + + EmitCtor(MapType(typeof(decimal)), new Type[] { MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(int)), MapType(typeof(bool)), MapType(typeof(byte)) }); + } + } + + internal void LoadValue(Guid value) + { + if (value == Guid.Empty) + { + LoadValue(typeof(Guid).GetField("Empty")); + } + else + { // note we're adding lots of shorts/bytes here - but at the IL level they are I4, not I1/I2 (which barely exist) + byte[] bytes = value.ToByteArray(); + int i = (bytes[0]) | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24); + LoadValue(i); + short s = (short)((bytes[4]) | (bytes[5] << 8)); + LoadValue(s); + s = (short)((bytes[6]) | (bytes[7] << 8)); + LoadValue(s); + for (i = 8; i <= 15; i++) + { + LoadValue(bytes[i]); + } + EmitCtor(MapType(typeof(Guid)), new Type[] { MapType(typeof(int)), MapType(typeof(short)), MapType(typeof(short)), + MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)), MapType(typeof(byte)) }); + } + } + + //internal void LoadValue(bool value) + //{ + // Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + //} + + internal void LoadSerializationContext() + { + LoadReaderWriter(); + LoadValue((isWriter ? typeof(ProtoWriter) : typeof(ProtoReader)).GetProperty("Context")); + } + + private readonly TypeModel model; + + internal Type MapType(Type type) + { + return model.MapType(type); + } + + private readonly ILVersion metadataVersion; + public ILVersion MetadataVersion { get { return metadataVersion; } } + public enum ILVersion + { + Net1, Net2 + } + + internal bool AllowInternal(PropertyInfo property) + { + return NonPublic ? true : InternalsVisible(Helpers.GetAssembly(property.DeclaringType)); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta new file mode 100644 index 00000000..b40174bd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a58d20a1d8c7730499ef29a11532d07e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs new file mode 100644 index 00000000..e7f0508f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs @@ -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 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta new file mode 100644 index 00000000..c9fedb05 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/CompilerDelegates.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b923d7ab8e95f740b059ca797596261 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/Local.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/Local.cs new file mode 100644 index 00000000..fd3dfa9a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/Local.cs @@ -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 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/Local.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/Local.cs.meta new file mode 100644 index 00000000..2767c29b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Compiler/Local.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07d12d9a9b7d45b498e28b7c39bdca01 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DataFormat.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DataFormat.cs new file mode 100644 index 00000000..4d97b4fc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DataFormat.cs @@ -0,0 +1,49 @@ + +namespace ProtoBuf +{ + /// + /// Sub-format to use when serializing/deserializing data + /// + public enum DataFormat + { + /// + /// Uses the default encoding for the data-type. + /// + Default, + + /// + /// 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. + /// + ZigZag, + + /// + /// 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. + /// + TwosComplement, + + /// + /// When applied to signed integer-based data (including Decimal), this + /// indicates that a fixed amount of space will be used. + /// + FixedSize, + + /// + /// When applied to a sub-message, indicates that the value should be treated + /// as group-delimited. + /// + Group, + + /// + /// When applied to members of types such as DateTime or TimeSpan, specifies + /// that the "well known" standardized representation should be use; DateTime uses Timestamp, + /// + /// + WellKnown + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DataFormat.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DataFormat.cs.meta new file mode 100644 index 00000000..644abad1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DataFormat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 875f2f7de4b03ff409de70d226359e8f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs new file mode 100644 index 00000000..0fd671fe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs @@ -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 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta new file mode 100644 index 00000000..f6163312 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.Serializable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a3aeec9c8a4c734e9ad022627502d1d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.cs new file mode 100644 index 00000000..7cc8cf8e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.cs @@ -0,0 +1,416 @@ +using System; +using System.Runtime.InteropServices; + +namespace ProtoBuf +{ + /// 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 + public readonly partial struct DiscriminatedUnionObject + { + + /// The value typed as Object + public readonly object Object; + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => Discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnionObject(int discriminator, object value) + { + Discriminator = discriminator; + Object = value; + } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnionObject value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + + /// The discriminator value + public int Discriminator { get; } + } + + /// 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 + [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 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + + private DiscriminatedUnion64(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion64(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion64 value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// 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 + [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 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + /// The value typed as Guid + [FieldOffset(8)] public readonly Guid Guid; + /// The value typed as Object + [FieldOffset(24)] public readonly object Object; + + private DiscriminatedUnion128Object(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128Object(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion128Object value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// 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 + [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 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + /// The value typed as Guid + [FieldOffset(8)] public readonly Guid Guid; + + private DiscriminatedUnion128(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion128(int discriminator, Guid? value) : this(value.HasValue ? discriminator : 0) { Guid = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion128 value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// 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 + [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 + + /// The value typed as Int64 + [FieldOffset(8)] public readonly long Int64; + /// The value typed as UInt64 + [FieldOffset(8)] public readonly ulong UInt64; + /// The value typed as Int32 + [FieldOffset(8)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(8)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(8)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(8)] public readonly float Single; + /// The value typed as Double + [FieldOffset(8)] public readonly double Double; + /// The value typed as DateTime + [FieldOffset(8)] public readonly DateTime DateTime; + /// The value typed as TimeSpan + [FieldOffset(8)] public readonly TimeSpan TimeSpan; + /// The value typed as Object + [FieldOffset(16)] public readonly object Object; + + private DiscriminatedUnion64Object(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, long value) : this(discriminator) { Int64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, ulong value) : this(discriminator) { UInt64 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, double value) : this(discriminator) { Double = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, DateTime? value) : this(value.HasValue ? discriminator: 0) { DateTime = value.GetValueOrDefault(); } + /// Create a new discriminated union value + public DiscriminatedUnion64Object(int discriminator, TimeSpan? value) : this(value.HasValue ? discriminator : 0) { TimeSpan = value.GetValueOrDefault(); } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion64Object value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// 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 + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion32 + { + [FieldOffset(0)] private readonly int _discriminator; + + /// The value typed as Int32 + [FieldOffset(4)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(4)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(4)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(4)] public readonly float Single; + + private DiscriminatedUnion32(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32(int discriminator, bool value) : this(discriminator) { Boolean = value; } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion32 value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } + + /// 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 + [StructLayout(LayoutKind.Explicit)] + public readonly partial struct DiscriminatedUnion32Object + { + [FieldOffset(0)] private readonly int _discriminator; + + /// The value typed as Int32 + [FieldOffset(4)] public readonly int Int32; + /// The value typed as UInt32 + [FieldOffset(4)] public readonly uint UInt32; + /// The value typed as Boolean + [FieldOffset(4)] public readonly bool Boolean; + /// The value typed as Single + [FieldOffset(4)] public readonly float Single; + /// The value typed as Object + [FieldOffset(8)] public readonly object Object; + + private DiscriminatedUnion32Object(int discriminator) : this() + { + _discriminator = discriminator; + } + + /// Indicates whether the specified discriminator is assigned + public bool Is(int discriminator) => _discriminator == discriminator; + + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, int value) : this(discriminator) { Int32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, uint value) : this(discriminator) { UInt32 = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, float value) : this(discriminator) { Single = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, bool value) : this(discriminator) { Boolean = value; } + /// Create a new discriminated union value + public DiscriminatedUnion32Object(int discriminator, object value) : this(value != null ? discriminator : 0) { Object = value; } + + /// Reset a value if the specified discriminator is assigned + public static void Reset(ref DiscriminatedUnion32Object value, int discriminator) + { + if (value.Discriminator == discriminator) value = default; + } + /// The discriminator value + public int Discriminator => _discriminator; + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta new file mode 100644 index 00000000..3268148b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/DiscriminatedUnion.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ab51817e163a1144bb8518368ba0a465 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Extensible.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Extensible.cs new file mode 100644 index 00000000..6bd528bc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Extensible.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using ProtoBuf.Meta; +using System.Collections; + +namespace ProtoBuf +{ + /// + /// 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. + /// + /// 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]. + /// + 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); + } + + /// + /// Retrieves the extension object for the current + /// instance, optionally creating it if it does not already exist. + /// + /// Should a new extension object be + /// created if it does not already exist? + /// The extension object if it exists (or was created), or null + /// if the extension object does not exist or is not available. + /// The createIfMissing argument is false during serialization, + /// and true during deserialization upon encountering unexpected fields. + protected virtual IExtension GetExtensionObject(bool createIfMissing) + { + return GetExtensionObject(ref extensionObject, createIfMissing); + } + + /// + /// Provides a simple, default implementation for extension support, + /// optionally creating it if it does not already exist. Designed to be called by + /// classes implementing . + /// + /// Should a new extension object be + /// created if it does not already exist? + /// The extension field to check (and possibly update). + /// The extension object if it exists (or was created), or null + /// if the extension object does not exist or is not available. + /// The createIfMissing argument is false during serialization, + /// and true during deserialization upon encountering unexpected fields. + public static IExtension GetExtensionObject(ref IExtension extensionObject, bool createIfMissing) + { + if (createIfMissing && extensionObject == null) + { + extensionObject = new BufferExtension(); + } + return extensionObject; + } + +#if !NO_RUNTIME + /// + /// 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. + /// + /// Note that appending a value does not remove the old value from + /// the stream; avoid repeatedly appending values for the same field. + /// The type of the value to append. + /// The extensible object to append the value to. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The value to append. + public static void AppendValue(IExtensible instance, int tag, TValue value) + { + AppendValue(instance, tag, DataFormat.Default, value); + } + + /// + /// 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. + /// + /// Note that appending a value does not remove the old value from + /// the stream; avoid repeatedly appending values for the same field. + /// The data-type of the field. + /// The data-format to use when encoding the value. + /// The extensible object to append the value to. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The value to append. + public static void AppendValue(IExtensible instance, int tag, DataFormat format, TValue value) + { + ExtensibleUtil.AppendExtendValue(RuntimeTypeModel.Default, instance, tag, format, value); + } + /// + /// 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. + /// + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The effective value of the field, or the default value if not found. + public static TValue GetValue(IExtensible instance, int tag) + { + return GetValue(instance, tag, DataFormat.Default); + } + + /// + /// 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. + /// + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// The effective value of the field, or the default value if not found. + public static TValue GetValue(IExtensible instance, int tag, DataFormat format) + { + TryGetValue(instance, tag, format, out TValue value); + return value; + } + + /// + /// 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. + /// + /// The data-type of the field. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(IExtensible instance, int tag, out TValue value) + { + return TryGetValue(instance, tag, DataFormat.Default, out value); + } + + /// + /// 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. + /// + /// The data-type of the field. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(IExtensible instance, int tag, DataFormat format, out TValue value) + { + return TryGetValue(instance, tag, format, false, out value); + } + + /// + /// 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. + /// + /// The data-type of the field. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// Allow tags that are present as part of the definition; for example, to query unknown enum values. + /// True if data for the field was present, false otherwise. + public static bool TryGetValue(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out TValue value) + { + value = default; + bool set = false; + foreach (TValue val in ExtensibleUtil.GetExtendedValues(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; + } + + /// + /// 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. + /// + /// The extended data is processed lazily as the enumerator is iterated. + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// An enumerator that yields each occurrence of the field. + public static IEnumerable GetValues(IExtensible instance, int tag) + { + return ExtensibleUtil.GetExtendedValues(instance, tag, DataFormat.Default, false, false); + } + + /// + /// 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. + /// + /// The extended data is processed lazily as the enumerator is iterated. + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// An enumerator that yields each occurrence of the field. + public static IEnumerable GetValues(IExtensible instance, int tag, DataFormat format) + { + return ExtensibleUtil.GetExtendedValues(instance, tag, format, false, false); + } +#endif + + /// + /// 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. + /// + /// The data-type of the field. + /// The model to use for configuration. + /// The effective value of the field, or the default value if not found. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// Allow tags that are present as part of the definition; for example, to query unknown enum values. + /// True if data for the field was present, false otherwise. + 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; + } + + /// + /// 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. + /// + /// The extended data is processed lazily as the enumerator is iterated. + /// The model to use for configuration. + /// The data-type of the field. + /// The extensible object to obtain the value from. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The data-format to use when decoding the value. + /// An enumerator that yields each occurrence of the field. + public static IEnumerable GetValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format) + { + return ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, false, false); + } + + /// + /// 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. + /// + /// Note that appending a value does not remove the old value from + /// the stream; avoid repeatedly appending values for the same field. + /// The model to use for configuration. + /// The data-format to use when encoding the value. + /// The extensible object to append the value to. + /// The field identifier; the tag should not be defined as a known data-field for the instance. + /// The value to append. + public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) + { + ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Extensible.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Extensible.cs.meta new file mode 100644 index 00000000..ac4ec367 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Extensible.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fc24b62dbd0b19642bce397e2b061aa0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ExtensibleUtil.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ExtensibleUtil.cs new file mode 100644 index 00000000..9cc16139 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ExtensibleUtil.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// 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<T> since we need to invoke + /// across classes + /// + internal static class ExtensibleUtil + { + +#if !NO_RUNTIME + /// + /// 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. + /// + internal static IEnumerable GetExtendedValues(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 + /// + /// 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. + /// + 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); + } + } + + // /// + // /// Stores the given value into the instance's stream; the serializer + // /// is inferred from TValue and format. + // /// + // /// Needs to be public to be callable thru reflection in Silverlight + // public static void AppendExtendValueTyped( + // TypeModel model, TSource instance, int tag, DataFormat format, TValue value) + // where TSource : class, IExtensible + // { + // AppendExtendValue(model, instance, tag, format, value); + // } + + } + +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta new file mode 100644 index 00000000..ea420c6f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ExtensibleUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc71d3f5e8f25ad41bb04ea933cee56e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/GlobalSuppressions.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/GlobalSuppressions.cs new file mode 100644 index 00000000..48b91900 Binary files /dev/null and b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/GlobalSuppressions.cs differ diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/GlobalSuppressions.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/GlobalSuppressions.cs.meta new file mode 100644 index 00000000..14ab4e34 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/GlobalSuppressions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c110f96e5d6da4f498bcb6d5fa673be7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Helpers.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Helpers.cs new file mode 100644 index 00000000..1a0491dd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Helpers.cs @@ -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 +{ + /// + /// 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. + /// + 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 members = declaringType.DeclaredMembers; + IList found = new List(); + 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(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(); + 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 + } + } + /// + /// Intended to be a direct map to regular TypeCode, but: + /// - with missing types + /// - existing on WinRT + /// + 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 + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Helpers.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Helpers.cs.meta new file mode 100644 index 00000000..d67edef1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Helpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 227f762ea287cdf42a9293ea6c481ff8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtensible.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtensible.cs new file mode 100644 index 00000000..b7c0b578 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtensible.cs @@ -0,0 +1,23 @@ + +namespace ProtoBuf +{ + /// + /// Indicates that the implementing type has support for protocol-buffer + /// extensions. + /// + /// Can be implemented by deriving from Extensible. + public interface IExtensible + { + /// + /// Retrieves the extension object for the current + /// instance, optionally creating it if it does not already exist. + /// + /// Should a new extension object be + /// created if it does not already exist? + /// The extension object if it exists (or was created), or null + /// if the extension object does not exist or is not available. + /// The createIfMissing argument is false during serialization, + /// and true during deserialization upon encountering unexpected fields. + IExtension GetExtensionObject(bool createIfMissing); + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtensible.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtensible.cs.meta new file mode 100644 index 00000000..3c8f29a5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtensible.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b9cd5092c5d6d9d4299fc0c88ebb9390 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtension.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtension.cs new file mode 100644 index 00000000..0a137aca --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtension.cs @@ -0,0 +1,58 @@ + +using System.IO; +namespace ProtoBuf +{ + /// + /// 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. + /// + public interface IExtension + { + /// + /// Requests a stream into which any unexpected fields can be persisted. + /// + /// A new stream suitable for storing data. + Stream BeginAppend(); + + /// + /// 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. + /// + /// The stream originally obtained by BeginAppend. + /// True if the append operation completed successfully. + void EndAppend(Stream stream, bool commit); + + /// + /// Requests a stream of the unexpected fields previously stored. + /// + /// A prepared stream of the unexpected fields. + Stream BeginQuery(); + + /// + /// Indicates that all unexpected fields have now been read. The + /// implementing class is responsible for closing the stream. + /// + /// The stream originally obtained by BeginQuery. + void EndQuery(Stream stream); + + /// + /// Requests the length of the raw binary stream; this is used + /// when serializing sub-entities to indicate the expected size. + /// + /// The length of the binary stream representing unexpected data. + int GetLength(); + } + + /// + /// Provides the ability to remove all existing extension data + /// + public interface IExtensionResettable : IExtension + { + /// + /// Remove all existing extension data + /// + void Reset(); + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtension.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtension.cs.meta new file mode 100644 index 00000000..d5da3406 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8018fb363175787478148842225e7d16 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoInputT.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoInputT.cs new file mode 100644 index 00000000..6eaa0ce2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoInputT.cs @@ -0,0 +1,13 @@ +namespace ProtoBuf +{ + /// + /// Represents the ability to deserialize values from an input of type + /// + public interface IProtoInput + { + /// + /// Deserialize a value from the input + /// + T Deserialize(TInput source, T value = default, object userState = null); + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoInputT.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoInputT.cs.meta new file mode 100644 index 00000000..a80bc62c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoInputT.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a6514bacfd3143a49a027f15434586f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoOutputT.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoOutputT.cs new file mode 100644 index 00000000..1c7dd420 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoOutputT.cs @@ -0,0 +1,55 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Represents the ability to serialize values to an output of type + /// + public interface IProtoOutput + { + /// + /// Serialize the provided value + /// + void Serialize(TOutput destination, T value, object userState = null); + } + + /// + /// Represents the ability to serialize values to an output of type + /// with pre-computation of the length + /// + public interface IMeasuredProtoOutput : IProtoOutput + { + /// + /// Measure the length of a value in advance of serialization + /// + MeasureState Measure(T value, object userState = null); + + /// + /// Serialize the previously measured value + /// + void Serialize(MeasureState measured, TOutput destination); + } + + /// + /// 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. + /// + public struct MeasureState : 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, and *work from that* + { + /// + /// Releases all resources associated with this value + /// + public void Dispose() => throw new NotImplementedException(); + + /// + /// Gets the calculated length of this serialize operation, in bytes + /// + public long Length => throw new NotImplementedException(); + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoOutputT.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoOutputT.cs.meta new file mode 100644 index 00000000..a6e7d866 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/IProtoOutputT.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17c52d90924d69d4aaf31925ea2c90bf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ImplicitFields.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ImplicitFields.cs new file mode 100644 index 00000000..211abdd0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ImplicitFields.cs @@ -0,0 +1,29 @@ +namespace ProtoBuf +{ + /// + /// 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). + /// + public enum ImplicitFields + { + /// + /// No members are serialized implicitly; all members require a suitable + /// attribute such as [ProtoMember]. This is the recmomended mode for + /// most scenarios. + /// + None = 0, + /// + /// Public properties and fields are eligible for implicit serialization; + /// this treats the public API as a contract. Ordering beings from ImplicitFirstTag. + /// + AllPublic = 1, + /// + /// Public and non-public fields are eligible for implicit serialization; + /// this acts as a state/implementation serializer. Ordering beings from ImplicitFirstTag. + /// + AllFields = 2 + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ImplicitFields.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ImplicitFields.cs.meta new file mode 100644 index 00000000..6da3beff --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ImplicitFields.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b838f9e3c6536bc438e7c31f73c49160 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/KeyValuePairProxy.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/KeyValuePairProxy.cs new file mode 100644 index 00000000..0da5761f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/KeyValuePairProxy.cs @@ -0,0 +1,44 @@ +//using System.Collections.Generic; + +//namespace ProtoBuf +//{ +// /// +// /// 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. +// /// +// [ProtoContract] +// public struct KeyValuePairSurrogate +// { +// private TKey key; +// private TValue value; +// /// +// /// The key of the pair. +// /// +// [ProtoMember(1, IsRequired = true)] +// public TKey Key { get { return key; } set { key = value; } } +// /// +// /// The value of the pair. +// /// +// [ProtoMember(2)] +// public TValue Value{ get { return value; } set { this.value = value; } } +// private KeyValuePairSurrogate(TKey key, TValue value) +// { +// this.key = key; +// this.value = value; +// } +// /// +// /// Convert a surrogate instance to a standard pair instance. +// /// +// public static implicit operator KeyValuePair (KeyValuePairSurrogate value) +// { +// return new KeyValuePair(value.key, value.value); +// } +// /// +// /// Convert a standard pair instance to a surrogate instance. +// /// +// public static implicit operator KeyValuePairSurrogate(KeyValuePair value) +// { +// return new KeyValuePairSurrogate(value.Key, value.Value); +// } +// } +//} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta new file mode 100644 index 00000000..c74b2841 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/KeyValuePairProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6221476e2339494cb5ee2bdc10ffd81 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta.meta new file mode 100644 index 00000000..5f17bddd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a70a85c13dddce74d9a6395c440c9156 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/AttributeMap.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/AttributeMap.cs new file mode 100644 index 00000000..5bab9422 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/AttributeMap.cs @@ -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(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(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 \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta new file mode 100644 index 00000000..d92ef3ad --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/AttributeMap.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3e64de7ef1358447843db562f78060f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/BasicList.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/BasicList.cs new file mode 100644 index 00000000..d1308f3e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/BasicList.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/BasicList.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/BasicList.cs.meta new file mode 100644 index 00000000..3304e307 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/BasicList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be5fc2a1ac0731a44b0365987d942485 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/CallbackSet.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/CallbackSet.cs new file mode 100644 index 00000000..8b085850 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/CallbackSet.cs @@ -0,0 +1,110 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Meta +{ + /// + /// Represents the set of serialization callbacks to be used when serializing/deserializing a type. + /// + 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; + + /// Called before serializing an instance + public MethodInfo BeforeSerialize + { + get { return beforeSerialize; } + set { beforeSerialize = SanityCheckCallback(metaType.Model, value); } + } + + /// Called before deserializing an instance + public MethodInfo BeforeDeserialize + { + get { return beforeDeserialize; } + set { beforeDeserialize = SanityCheckCallback(metaType.Model, value); } + } + + /// Called after serializing an instance + public MethodInfo AfterSerialize + { + get { return afterSerialize; } + set { afterSerialize = SanityCheckCallback(metaType.Model, value); } + } + + /// Called after deserializing an instance + public MethodInfo AfterDeserialize + { + get { return afterDeserialize; } + set { afterDeserialize = SanityCheckCallback(metaType.Model, value); } + } + + /// + /// True if any callback is set, else False + /// + public bool NonTrivial + { + get + { + return beforeSerialize != null || beforeDeserialize != null + || afterSerialize != null || afterDeserialize != null; + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta new file mode 100644 index 00000000..0c6da409 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/CallbackSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de0e7cb7bfcf4904aa31e910f241a8aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/MetaType.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/MetaType.cs new file mode 100644 index 00000000..8d9bed66 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/MetaType.cs @@ -0,0 +1,2171 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Text; +using ProtoBuf.Serializers; +using System.Reflection; +using System.Collections.Generic; + +#if PROFILE259 +using System.Linq; +#endif + +namespace ProtoBuf.Meta +{ + /// + /// Represents a type at runtime for use with protobuf, allowing the field mappings (etc) to be defined + /// + public class MetaType : ISerializerProxy + { + internal sealed class Comparer : IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + public int Compare(object x, object y) + { + return Compare(x as MetaType, y as MetaType); + } + public int Compare(MetaType x, MetaType y) + { + if (ReferenceEquals(x, y)) return 0; + if (x == null) return -1; + if (y == null) return 1; + + return string.Compare(x.GetSchemaTypeName(), y.GetSchemaTypeName(), StringComparison.Ordinal); + } + } + /// + /// Get the name of the type being represented + /// + public override string ToString() + { + return type.ToString(); + } + + IProtoSerializer ISerializerProxy.Serializer => Serializer; + private MetaType baseType; + + /// + /// Gets the base-type for this type + /// + public MetaType BaseType => baseType; + + internal TypeModel Model => model; + + /// + /// When used to compile a model, should public serialization/deserialzation methods + /// be included for this type? + /// + public bool IncludeSerializerMethod + { // negated to minimize common-case / initializer + get { return !HasFlag(OPTIONS_PrivateOnApi); } + set { SetFlag(OPTIONS_PrivateOnApi, !value, true); } + } + + /// + /// Should this type be treated as a reference by default? + /// + public bool AsReferenceDefault + { + get { return HasFlag(OPTIONS_AsReferenceDefault); } + set { SetFlag(OPTIONS_AsReferenceDefault, value, true); } + } + + private BasicList subTypes; + private bool IsValidSubType(Type subType) + { +#if COREFX || PROFILE259 + return typeInfo.IsAssignableFrom(subType.GetTypeInfo()); +#else + return type.IsAssignableFrom(subType); +#endif + } + /// + /// Adds a known sub-type to the inheritance model + /// + public MetaType AddSubType(int fieldNumber, Type derivedType) + { + return AddSubType(fieldNumber, derivedType, DataFormat.Default); + } + /// + /// Adds a known sub-type to the inheritance model + /// + public MetaType AddSubType(int fieldNumber, Type derivedType, DataFormat dataFormat) + { + if (derivedType == null) throw new ArgumentNullException("derivedType"); + if (fieldNumber < 1) throw new ArgumentOutOfRangeException("fieldNumber"); +#if COREFX || COREFX || PROFILE259 + if (!(typeInfo.IsClass || typeInfo.IsInterface) || typeInfo.IsSealed) { +#else + if (!(type.IsClass || type.IsInterface) || type.IsSealed) + { +#endif + throw new InvalidOperationException("Sub-types can only be added to non-sealed classes"); + } + if (!IsValidSubType(derivedType)) + { + throw new ArgumentException(derivedType.Name + " is not a valid sub-type of " + type.Name, "derivedType"); + } + MetaType derivedMeta = model[derivedType]; + ThrowIfFrozen(); + derivedMeta.ThrowIfFrozen(); + SubType subType = new SubType(fieldNumber, derivedMeta, dataFormat); + ThrowIfFrozen(); + + derivedMeta.SetBaseType(this); // includes ThrowIfFrozen + if (subTypes == null) subTypes = new BasicList(); + subTypes.Add(subType); + model.ResetKeyCache(); + return this; + } +#if COREFX || PROFILE259 + internal static readonly TypeInfo ienumerable = typeof(IEnumerable).GetTypeInfo(); +#else + internal static readonly Type ienumerable = typeof(IEnumerable); +#endif + private void SetBaseType(MetaType baseType) + { + if (baseType == null) throw new ArgumentNullException("baseType"); + if (this.baseType == baseType) return; + if (this.baseType != null) throw new InvalidOperationException($"Type '{this.baseType.Type.FullName}' can only participate in one inheritance hierarchy"); + + MetaType type = baseType; + while (type != null) + { + if (ReferenceEquals(type, this)) throw new InvalidOperationException($"Cyclic inheritance of '{this.baseType.Type.FullName}' is not allowed"); + type = type.baseType; + } + this.baseType = baseType; + } + + private CallbackSet callbacks; + + /// + /// Indicates whether the current type has defined callbacks + /// + public bool HasCallbacks => callbacks != null && callbacks.NonTrivial; + + /// + /// Indicates whether the current type has defined subtypes + /// + public bool HasSubtypes => subTypes != null && subTypes.Count != 0; + + /// + /// Returns the set of callbacks defined for this type + /// + public CallbackSet Callbacks + { + get + { + if (callbacks == null) callbacks = new CallbackSet(this); + return callbacks; + } + } + + private bool IsValueType + { + get + { +#if COREFX || PROFILE259 + return typeInfo.IsValueType; +#else + return type.IsValueType; +#endif + } + } + /// + /// Assigns the callbacks to use during serialiation/deserialization. + /// + /// The method (or null) called before serialization begins. + /// The method (or null) called when serialization is complete. + /// The method (or null) called before deserialization begins (or when a new instance is created during deserialization). + /// The method (or null) called when deserialization is complete. + /// The set of callbacks. + public MetaType SetCallbacks(MethodInfo beforeSerialize, MethodInfo afterSerialize, MethodInfo beforeDeserialize, MethodInfo afterDeserialize) + { + CallbackSet callbacks = Callbacks; + callbacks.BeforeSerialize = beforeSerialize; + callbacks.AfterSerialize = afterSerialize; + callbacks.BeforeDeserialize = beforeDeserialize; + callbacks.AfterDeserialize = afterDeserialize; + return this; + } + /// + /// Assigns the callbacks to use during serialiation/deserialization. + /// + /// The name of the method (or null) called before serialization begins. + /// The name of the method (or null) called when serialization is complete. + /// The name of the method (or null) called before deserialization begins (or when a new instance is created during deserialization). + /// The name of the method (or null) called when deserialization is complete. + /// The set of callbacks. + public MetaType SetCallbacks(string beforeSerialize, string afterSerialize, string beforeDeserialize, string afterDeserialize) + { + if (IsValueType) throw new InvalidOperationException(); + CallbackSet callbacks = Callbacks; + callbacks.BeforeSerialize = ResolveMethod(beforeSerialize, true); + callbacks.AfterSerialize = ResolveMethod(afterSerialize, true); + callbacks.BeforeDeserialize = ResolveMethod(beforeDeserialize, true); + callbacks.AfterDeserialize = ResolveMethod(afterDeserialize, true); + return this; + } + + /// + /// Returns the public Type name of this Type used in serialization + /// + public string GetSchemaTypeName() + { + if (surrogate != null) return model[surrogate].GetSchemaTypeName(); + + if (!string.IsNullOrEmpty(name)) return name; + + string typeName = type.Name; + if (type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsGenericType) + { + var sb = new StringBuilder(typeName); + int split = typeName.IndexOf('`'); + if (split >= 0) sb.Length = split; + foreach (Type arg in type +#if COREFX || PROFILE259 + .GetTypeInfo().GenericTypeArguments +#else + .GetGenericArguments() +#endif + ) + { + sb.Append('_'); + Type tmp = arg; + int key = model.GetKey(ref tmp); + MetaType mt; + if (key >= 0 && (mt = model[tmp]) != null && mt.surrogate == null) // <=== need to exclude surrogate to avoid chance of infinite loop + { + + sb.Append(mt.GetSchemaTypeName()); + } + else + { + sb.Append(tmp.Name); + } + } + return sb.ToString(); + } + + return typeName; + } + + private string name; + + /// + /// Gets or sets the name of this contract. + /// + public string Name + { + get + { + return name; + } + set + { + ThrowIfFrozen(); + name = value; + } + } + + private MethodInfo factory; + /// + /// Designate a factory-method to use to create instances of this type + /// + public MetaType SetFactory(MethodInfo factory) + { + model.VerifyFactory(factory, type); + ThrowIfFrozen(); + this.factory = factory; + return this; + } + + /// + /// Designate a factory-method to use to create instances of this type + /// + public MetaType SetFactory(string factory) + { + return SetFactory(ResolveMethod(factory, false)); + } + + private MethodInfo ResolveMethod(string name, bool instance) + { + if (string.IsNullOrEmpty(name)) return null; +#if COREFX + return instance ? Helpers.GetInstanceMethod(typeInfo, name) : Helpers.GetStaticMethod(typeInfo, name); +#else + return instance ? Helpers.GetInstanceMethod(type, name) : Helpers.GetStaticMethod(type, name); +#endif + } + + private readonly RuntimeTypeModel model; + + internal static Exception InbuiltType(Type type) + { + return new ArgumentException("Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName); + } + + internal MetaType(RuntimeTypeModel model, Type type, MethodInfo factory) + { + this.factory = factory; + if (model == null) throw new ArgumentNullException("model"); + if (type == null) throw new ArgumentNullException("type"); + + if (type.IsArray) throw InbuiltType(type); + IProtoSerializer coreSerializer = model.TryGetBasicTypeSerializer(type); + if (coreSerializer != null) + { + throw InbuiltType(type); + } + + this.type = type; +#if COREFX || PROFILE259 + this.typeInfo = type.GetTypeInfo(); +#endif + this.model = model; + + if (Helpers.IsEnum(type)) + { +#if COREFX || PROFILE259 + EnumPassthru = typeInfo.IsDefined(typeof(FlagsAttribute), false); +#else + EnumPassthru = type.IsDefined(model.MapType(typeof(FlagsAttribute)), false); +#endif + } + } +#if COREFX || PROFILE259 + private readonly TypeInfo typeInfo; +#endif + /// + /// Throws an exception if the type has been made immutable + /// + protected internal void ThrowIfFrozen() + { + if ((flags & OPTIONS_Frozen) != 0) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated for " + type.FullName); + } + + // internal void Freeze() { flags |= OPTIONS_Frozen; } + + private readonly Type type; + /// + /// The runtime type that the meta-type represents + /// + public Type Type => type; + + private IProtoTypeSerializer serializer; + internal IProtoTypeSerializer Serializer + { + get + { + if (serializer == null) + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + if (serializer == null) + { // double-check, but our main purpse with this lock is to ensure thread-safety with + // serializers needing to wait until another thread has finished adding the properties + SetFlag(OPTIONS_Frozen, true, false); + serializer = BuildSerializer(); +#if FEAT_COMPILER + if (model.AutoCompile) CompileInPlace(); +#endif + } + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + return serializer; + } + } + internal bool IsList + { + get + { + Type itemType = IgnoreListHandling ? null : TypeModel.GetListItemType(model, type); + return itemType != null; + } + } + private IProtoTypeSerializer BuildSerializer() + { + if (Helpers.IsEnum(type)) + { + return new TagDecorator(ProtoBuf.Serializer.ListItemTag, WireType.Variant, false, new EnumSerializer(type, GetEnumMap())); + } + Type itemType = IgnoreListHandling ? null : TypeModel.GetListItemType(model, type); + if (itemType != null) + { + if (surrogate != null) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot use a surrogate"); + } + if (subTypes != null && subTypes.Count != 0) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed"); + } + Type defaultType = null; + ResolveListTypes(model, type, ref itemType, ref defaultType); + ValueMember fakeMember = new ValueMember(model, ProtoBuf.Serializer.ListItemTag, type, itemType, defaultType, DataFormat.Default); + return new TypeSerializer(model, type, new int[] { ProtoBuf.Serializer.ListItemTag }, new IProtoSerializer[] { fakeMember.Serializer }, null, true, true, null, constructType, factory); + } + if (surrogate != null) + { + MetaType mt = model[surrogate], mtBase; + while ((mtBase = mt.baseType) != null) { mt = mtBase; } + return new SurrogateSerializer(model, type, surrogate, mt.Serializer); + } + if (IsAutoTuple) + { + ConstructorInfo ctor = ResolveTupleConstructor(type, out MemberInfo[] mapping); + if (ctor == null) throw new InvalidOperationException(); + return new TupleSerializer(model, ctor, mapping); + } + + fields.Trim(); + int fieldCount = fields.Count; + int subTypeCount = subTypes == null ? 0 : subTypes.Count; + int[] fieldNumbers = new int[fieldCount + subTypeCount]; + IProtoSerializer[] serializers = new IProtoSerializer[fieldCount + subTypeCount]; + int i = 0; + if (subTypeCount != 0) + { + foreach (SubType subType in subTypes) + { +#if COREFX || PROFILE259 + if (!subType.DerivedType.IgnoreListHandling && ienumerable.IsAssignableFrom(subType.DerivedType.Type.GetTypeInfo())) +#else + if (!subType.DerivedType.IgnoreListHandling && model.MapType(ienumerable).IsAssignableFrom(subType.DerivedType.Type)) +#endif + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a subclass"); + } + fieldNumbers[i] = subType.FieldNumber; + serializers[i++] = subType.Serializer; + } + } + if (fieldCount != 0) + { + foreach (ValueMember member in fields) + { + fieldNumbers[i] = member.FieldNumber; + serializers[i++] = member.Serializer; + } + } + + BasicList baseCtorCallbacks = null; + MetaType tmp = BaseType; + + while (tmp != null) + { + MethodInfo method = tmp.HasCallbacks ? tmp.Callbacks.BeforeDeserialize : null; + if (method != null) + { + if (baseCtorCallbacks == null) baseCtorCallbacks = new BasicList(); + baseCtorCallbacks.Add(method); + } + tmp = tmp.BaseType; + } + MethodInfo[] arr = null; + if (baseCtorCallbacks != null) + { + arr = new MethodInfo[baseCtorCallbacks.Count]; + baseCtorCallbacks.CopyTo(arr, 0); + Array.Reverse(arr); + } + return new TypeSerializer(model, type, fieldNumbers, serializers, arr, baseType == null, UseConstructor, callbacks, constructType, factory); + } + + [Flags] + internal enum AttributeFamily + { + None = 0, ProtoBuf = 1, DataContractSerialier = 2, XmlSerializer = 4, AutoTuple = 8 + } + static Type GetBaseType(MetaType type) + { +#if COREFX || PROFILE259 + return type.typeInfo.BaseType; +#else + return type.type.BaseType; +#endif + } + internal static bool GetAsReferenceDefault(RuntimeTypeModel model, Type type) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + if (Helpers.IsEnum(type)) return false; // never as-ref + AttributeMap[] typeAttribs = AttributeMap.Create(model, type, false); + for (int i = 0; i < typeAttribs.Length; i++) + { + if (typeAttribs[i].AttributeType.FullName == "ProtoBuf.ProtoContractAttribute") + { + if (typeAttribs[i].TryGet("AsReferenceDefault", out object tmp)) return (bool)tmp; + } + } + return false; + } + + internal void ApplyDefaultBehaviour() + { + TypeAddedEventArgs args = null; // allows us to share the event-args between events + RuntimeTypeModel.OnBeforeApplyDefaultBehaviour(this, ref args); + if (args == null || args.ApplyDefaultBehaviour) ApplyDefaultBehaviourImpl(); + RuntimeTypeModel.OnAfterApplyDefaultBehaviour(this, ref args); + } + + internal void ApplyDefaultBehaviourImpl() + { + Type baseType = GetBaseType(this); + if (baseType != null && model.FindWithoutAdd(baseType) == null + && GetContractFamily(model, baseType, null) != MetaType.AttributeFamily.None) + { + model.FindOrAddAuto(baseType, true, false, false); + } + + AttributeMap[] typeAttribs = AttributeMap.Create(model, type, false); + AttributeFamily family = GetContractFamily(model, type, typeAttribs); + if (family == AttributeFamily.AutoTuple) + { + SetFlag(OPTIONS_AutoTuple, true, true); + } + bool isEnum = !EnumPassthru && Helpers.IsEnum(type); + if (family == AttributeFamily.None && !isEnum) return; // and you'd like me to do what, exactly? + + bool enumShouldUseImplicitPassThru = isEnum; + BasicList partialIgnores = null, partialMembers = null; + int dataMemberOffset = 0, implicitFirstTag = 1; + bool inferTagByName = model.InferTagFromNameDefault; + ImplicitFields implicitMode = ImplicitFields.None; + string name = null; + for (int i = 0; i < typeAttribs.Length; i++) + { + AttributeMap item = (AttributeMap)typeAttribs[i]; + object tmp; + string fullAttributeTypeName = item.AttributeType.FullName; + if (!isEnum && fullAttributeTypeName == "ProtoBuf.ProtoIncludeAttribute") + { + int tag = 0; + if (item.TryGet("tag", out tmp)) tag = (int)tmp; + DataFormat dataFormat = DataFormat.Default; + if (item.TryGet("DataFormat", out tmp)) + { + dataFormat = (DataFormat)(int)tmp; + } + Type knownType = null; + try + { + if (item.TryGet("knownTypeName", out tmp)) knownType = model.GetType((string)tmp, type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .Assembly); + else if (item.TryGet("knownType", out tmp)) knownType = (Type)tmp; + } + catch (Exception ex) + { + throw new InvalidOperationException("Unable to resolve sub-type of: " + type.FullName, ex); + } + if (knownType == null) + { + throw new InvalidOperationException("Unable to resolve sub-type of: " + type.FullName); + } + if (IsValidSubType(knownType)) AddSubType(tag, knownType, dataFormat); + } + + if (fullAttributeTypeName == "ProtoBuf.ProtoPartialIgnoreAttribute") + { + if (item.TryGet(nameof(ProtoPartialIgnoreAttribute.MemberName), out tmp) && tmp != null) + { + if (partialIgnores == null) partialIgnores = new BasicList(); + partialIgnores.Add((string)tmp); + } + } + if (!isEnum && fullAttributeTypeName == "ProtoBuf.ProtoPartialMemberAttribute") + { + if (partialMembers == null) partialMembers = new BasicList(); + partialMembers.Add(item); + } + + if (fullAttributeTypeName == "ProtoBuf.ProtoContractAttribute") + { + if (item.TryGet(nameof(ProtoContractAttribute.Name), out tmp)) name = (string)tmp; + if (Helpers.IsEnum(type)) // note this is subtly different to isEnum; want to do this even if [Flags] + { + if (item.TryGet(nameof(ProtoContractAttribute.EnumPassthruHasValue), false, out tmp) && (bool)tmp) + { + if (item.TryGet(nameof(ProtoContractAttribute.EnumPassthru), out tmp)) + { + EnumPassthru = (bool)tmp; + enumShouldUseImplicitPassThru = false; + if (EnumPassthru) isEnum = false; // no longer treated as an enum + } + } + } + else + { + if (item.TryGet(nameof(ProtoContractAttribute.DataMemberOffset), out tmp)) dataMemberOffset = (int)tmp; + + if (item.TryGet(nameof(ProtoContractAttribute.InferTagFromNameHasValue), false, out tmp) && (bool)tmp) + { + if (item.TryGet(nameof(ProtoContractAttribute.InferTagFromName), out tmp)) inferTagByName = (bool)tmp; + } + + if (item.TryGet(nameof(ProtoContractAttribute.ImplicitFields), out tmp) && tmp != null) + { + implicitMode = (ImplicitFields)(int)tmp; // note that this uses the bizarre unboxing rules of enums/underlying-types + } + + if (item.TryGet(nameof(ProtoContractAttribute.SkipConstructor), out tmp)) UseConstructor = !(bool)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.IgnoreListHandling), out tmp)) IgnoreListHandling = (bool)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.AsReferenceDefault), out tmp)) AsReferenceDefault = (bool)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.ImplicitFirstTag), out tmp) && (int)tmp > 0) implicitFirstTag = (int)tmp; + if (item.TryGet(nameof(ProtoContractAttribute.IsGroup), out tmp)) IsGroup = (bool)tmp; + + if (item.TryGet(nameof(ProtoContractAttribute.Surrogate), out tmp)) + { + SetSurrogate((Type)tmp); + } + } + } + + if (fullAttributeTypeName == "System.Runtime.Serialization.DataContractAttribute") + { + if (name == null && item.TryGet("Name", out tmp)) name = (string)tmp; + } + if (fullAttributeTypeName == "System.Xml.Serialization.XmlTypeAttribute") + { + if (name == null && item.TryGet("TypeName", out tmp)) name = (string)tmp; + } + } + if (!string.IsNullOrEmpty(name)) Name = name; + if (implicitMode != ImplicitFields.None) + { + family &= AttributeFamily.ProtoBuf; // with implicit fields, **only** proto attributes are important + } + MethodInfo[] callbacks = null; + + BasicList members = new BasicList(); + +#if PROFILE259 + IEnumerable foundList; + if(isEnum) { + foundList = type.GetRuntimeFields(); + } + else + { + List list = new List(); + foreach(PropertyInfo prop in type.GetRuntimeProperties()) { + MethodInfo getter = Helpers.GetGetMethod(prop, false, false); + if(getter != null && !getter.IsStatic) list.Add(prop); + } + foreach(FieldInfo fld in type.GetRuntimeFields()) if(fld.IsPublic && !fld.IsStatic) list.Add(fld); + foreach(MethodInfo mthd in type.GetRuntimeMethods()) if(mthd.IsPublic && !mthd.IsStatic) list.Add(mthd); + foundList = list; + } +#else + MemberInfo[] foundList = type.GetMembers(isEnum ? BindingFlags.Public | BindingFlags.Static + : BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); +#endif + bool hasConflictingEnumValue = false; + foreach (MemberInfo member in foundList) + { + if (member.DeclaringType != type) continue; + if (member.IsDefined(model.MapType(typeof(ProtoIgnoreAttribute)), true)) continue; + if (partialIgnores != null && partialIgnores.Contains(member.Name)) continue; + + bool forced = false, isPublic, isField; + Type effectiveType; + + if (member is PropertyInfo property) + { + if (isEnum) continue; // wasn't expecting any props! + MemberInfo backingField = null; + if (!property.CanWrite) + { + // roslyn automatically implemented properties, in particular for get-only properties: <{Name}>k__BackingField; + var backingFieldName = $"<{property.Name}>k__BackingField"; + foreach (var fieldMemeber in foundList) + { + if ((fieldMemeber as FieldInfo != null) && fieldMemeber.Name == backingFieldName) + { + backingField = fieldMemeber; + break; + } + } + } + effectiveType = property.PropertyType; + isPublic = Helpers.GetGetMethod(property, false, false) != null; + isField = false; + ApplyDefaultBehaviour_AddMembers(model, family, isEnum, partialMembers, dataMemberOffset, inferTagByName, implicitMode, members, member, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue, backingField); + } + else if (member is FieldInfo field) + { + effectiveType = field.FieldType; + isPublic = field.IsPublic; + isField = true; + if (isEnum && !field.IsStatic) + { // only care about static things on enums; WinRT has a __value instance field! + continue; + } + ApplyDefaultBehaviour_AddMembers(model, family, isEnum, partialMembers, dataMemberOffset, inferTagByName, implicitMode, members, member, ref forced, isPublic, isField, ref effectiveType, ref hasConflictingEnumValue); + } + else if (member is MethodInfo method) + { + if (isEnum) continue; + AttributeMap[] memberAttribs = AttributeMap.Create(model, method, false); + if (memberAttribs != null && memberAttribs.Length > 0) + { + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoBeforeSerializationAttribute", ref callbacks, 0); + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoAfterSerializationAttribute", ref callbacks, 1); + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoBeforeDeserializationAttribute", ref callbacks, 2); + CheckForCallback(method, memberAttribs, "ProtoBuf.ProtoAfterDeserializationAttribute", ref callbacks, 3); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnSerializingAttribute", ref callbacks, 4); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnSerializedAttribute", ref callbacks, 5); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnDeserializingAttribute", ref callbacks, 6); + CheckForCallback(method, memberAttribs, "System.Runtime.Serialization.OnDeserializedAttribute", ref callbacks, 7); + } + } + } + + if (isEnum && enumShouldUseImplicitPassThru && !hasConflictingEnumValue) + { + EnumPassthru = true; + // but leave isEnum alone + } + var arr = new ProtoMemberAttribute[members.Count]; + members.CopyTo(arr, 0); + + if (inferTagByName || implicitMode != ImplicitFields.None) + { + Array.Sort(arr); + int nextTag = implicitFirstTag; + foreach (ProtoMemberAttribute normalizedAttribute in arr) + { + if (!normalizedAttribute.TagIsPinned) // if ProtoMember etc sets a tag, we'll trust it + { + normalizedAttribute.Rebase(nextTag++); + } + } + } + + foreach (ProtoMemberAttribute normalizedAttribute in arr) + { + ValueMember vm = ApplyDefaultBehaviour(isEnum, normalizedAttribute); + if (vm != null) + { + Add(vm); + } + } + + if (callbacks != null) + { + SetCallbacks(Coalesce(callbacks, 0, 4), Coalesce(callbacks, 1, 5), + Coalesce(callbacks, 2, 6), Coalesce(callbacks, 3, 7)); + } + } + + private static void ApplyDefaultBehaviour_AddMembers(TypeModel model, AttributeFamily family, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferTagByName, ImplicitFields implicitMode, BasicList members, MemberInfo member, ref bool forced, bool isPublic, bool isField, ref Type effectiveType, ref bool hasConflictingEnumValue, MemberInfo backingMember = null) + { + switch (implicitMode) + { + case ImplicitFields.AllFields: + if (isField) forced = true; + break; + case ImplicitFields.AllPublic: + if (isPublic) forced = true; + break; + } + + // we just don't like delegate types ;p +#if COREFX || PROFILE259 + if (effectiveType.GetTypeInfo().IsSubclassOf(typeof(Delegate))) effectiveType = null; +#else + if (effectiveType.IsSubclassOf(model.MapType(typeof(Delegate)))) effectiveType = null; +#endif + if (effectiveType != null) + { + ProtoMemberAttribute normalizedAttribute = NormalizeProtoMember(model, member, family, forced, isEnum, partialMembers, dataMemberOffset, inferTagByName, ref hasConflictingEnumValue, backingMember); + if (normalizedAttribute != null) members.Add(normalizedAttribute); + } + } + + static MethodInfo Coalesce(MethodInfo[] arr, int x, int y) + { + MethodInfo mi = arr[x]; + if (mi == null) mi = arr[y]; + return mi; + } + + internal static AttributeFamily GetContractFamily(RuntimeTypeModel model, Type type, AttributeMap[] attributes) + { + AttributeFamily family = AttributeFamily.None; + + if (attributes == null) attributes = AttributeMap.Create(model, type, false); + + for (int i = 0; i < attributes.Length; i++) + { + switch (attributes[i].AttributeType.FullName) + { + case "ProtoBuf.ProtoContractAttribute": + bool tmp = false; + GetFieldBoolean(ref tmp, attributes[i], "UseProtoMembersOnly"); + if (tmp) return AttributeFamily.ProtoBuf; + family |= AttributeFamily.ProtoBuf; + break; + case "System.Xml.Serialization.XmlTypeAttribute": + if (!model.AutoAddProtoContractTypesOnly) + { + family |= AttributeFamily.XmlSerializer; + } + break; + case "System.Runtime.Serialization.DataContractAttribute": + if (!model.AutoAddProtoContractTypesOnly) + { + family |= AttributeFamily.DataContractSerialier; + } + break; + } + } + if (family == AttributeFamily.None) + { // check for obvious tuples + if (ResolveTupleConstructor(type, out MemberInfo[] mapping) != null) + { + family |= AttributeFamily.AutoTuple; + } + } + return family; + } + internal static ConstructorInfo ResolveTupleConstructor(Type type, out MemberInfo[] mappedMembers) + { + mappedMembers = null; + if (type == null) throw new ArgumentNullException(nameof(type)); +#if COREFX || PROFILE259 + TypeInfo typeInfo = type.GetTypeInfo(); + if (typeInfo.IsAbstract) return null; // as if! + ConstructorInfo[] ctors = Helpers.GetConstructors(typeInfo, false); +#else + if (type.IsAbstract) return null; // as if! + ConstructorInfo[] ctors = Helpers.GetConstructors(type, false); +#endif + // need to have an interesting constructor to bother even checking this stuff + if (ctors.Length == 0 || (ctors.Length == 1 && ctors[0].GetParameters().Length == 0)) return null; + + MemberInfo[] fieldsPropsUnfiltered = Helpers.GetInstanceFieldsAndProperties(type, true); + BasicList memberList = new BasicList(); + // for most types we'll enforce that you need readonly, because that is what protobuf-net + // always did historically; but: if you smell so much like a Tuple that it is *in your name*, + // we'll let you past that + bool demandReadOnly = type.Name.IndexOf("Tuple", StringComparison.OrdinalIgnoreCase) < 0; + for (int i = 0; i < fieldsPropsUnfiltered.Length; i++) + { + if (fieldsPropsUnfiltered[i] is PropertyInfo prop) + { + if (!prop.CanRead) return null; // no use if can't read + if (demandReadOnly && prop.CanWrite && Helpers.GetSetMethod(prop, false, false) != null) return null; // don't allow a public set (need to allow non-public to handle Mono's KeyValuePair<,>) + memberList.Add(prop); + } + else + { + if (fieldsPropsUnfiltered[i] is FieldInfo field) + { + if (demandReadOnly && !field.IsInitOnly) return null; // all public fields must be readonly to be counted a tuple + memberList.Add(field); + } + } + } + if (memberList.Count == 0) + { + return null; + } + + MemberInfo[] members = new MemberInfo[memberList.Count]; + memberList.CopyTo(members, 0); + + int[] mapping = new int[members.Length]; + int found = 0; + ConstructorInfo result = null; + mappedMembers = new MemberInfo[mapping.Length]; + for (int i = 0; i < ctors.Length; i++) + { + ParameterInfo[] parameters = ctors[i].GetParameters(); + + if (parameters.Length != members.Length) continue; + + // reset the mappings to test + for (int j = 0; j < mapping.Length; j++) mapping[j] = -1; + + for (int j = 0; j < parameters.Length; j++) + { + for (int k = 0; k < members.Length; k++) + { + if (string.Compare(parameters[j].Name, members[k].Name, StringComparison.OrdinalIgnoreCase) != 0) continue; + Type memberType = Helpers.GetMemberType(members[k]); + if (memberType != parameters[j].ParameterType) continue; + + mapping[j] = k; + } + } + // did we map all? + bool notMapped = false; + for (int j = 0; j < mapping.Length; j++) + { + if (mapping[j] < 0) + { + notMapped = true; + break; + } + mappedMembers[j] = members[mapping[j]]; + } + + if (notMapped) continue; + found++; + result = ctors[i]; + + } + return found == 1 ? result : null; + } + + private static void CheckForCallback(MethodInfo method, AttributeMap[] attributes, string callbackTypeName, ref MethodInfo[] callbacks, int index) + { + for (int i = 0; i < attributes.Length; i++) + { + if (attributes[i].AttributeType.FullName == callbackTypeName) + { + if (callbacks == null) { callbacks = new MethodInfo[8]; } + else if (callbacks[index] != null) + { +#if COREFX || PROFILE259 + Type reflected = method.DeclaringType; +#else + Type reflected = method.ReflectedType; +#endif + throw new ProtoException("Duplicate " + callbackTypeName + " callbacks on " + reflected.FullName); + } + callbacks[index] = method; + } + } + } + private static bool HasFamily(AttributeFamily value, AttributeFamily required) + { + return (value & required) == required; + } + + private static ProtoMemberAttribute NormalizeProtoMember(TypeModel model, MemberInfo member, AttributeFamily family, bool forced, bool isEnum, BasicList partialMembers, int dataMemberOffset, bool inferByTagName, ref bool hasConflictingEnumValue, MemberInfo backingMember = null) + { + if (member == null || (family == AttributeFamily.None && !isEnum)) return null; // nix + int fieldNumber = int.MinValue, minAcceptFieldNumber = inferByTagName ? -1 : 1; + string name = null; + bool isPacked = false, ignore = false, done = false, isRequired = false, asReference = false, asReferenceHasValue = false, dynamicType = false, tagIsPinned = false, overwriteList = false; + DataFormat dataFormat = DataFormat.Default; + if (isEnum) forced = true; + AttributeMap[] attribs = AttributeMap.Create(model, member, true); + AttributeMap attrib; + + if (isEnum) + { + attrib = GetAttribute(attribs, "ProtoBuf.ProtoIgnoreAttribute"); + if (attrib != null) + { + ignore = true; + } + else + { + attrib = GetAttribute(attribs, "ProtoBuf.ProtoEnumAttribute"); +#if PORTABLE || CF || COREFX || PROFILE259 + fieldNumber = Convert.ToInt32(((FieldInfo)member).GetValue(null)); +#else + fieldNumber = Convert.ToInt32(((FieldInfo)member).GetRawConstantValue()); +#endif + if (attrib != null) + { + GetFieldName(ref name, attrib, nameof(ProtoEnumAttribute.Name)); + + if ((bool)Helpers.GetInstanceMethod(attrib.AttributeType +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + , nameof(ProtoEnumAttribute.HasValue)).Invoke(attrib.Target, null)) + { + if (attrib.TryGet(nameof(ProtoEnumAttribute.Value), out object tmp)) + { + if (fieldNumber != (int)tmp) + { + hasConflictingEnumValue = true; + } + fieldNumber = (int)tmp; + } + } + } + + } + done = true; + } + + if (!ignore && !done) // always consider ProtoMember + { + attrib = GetAttribute(attribs, "ProtoBuf.ProtoMemberAttribute"); + GetIgnore(ref ignore, attrib, attribs, "ProtoBuf.ProtoIgnoreAttribute"); + + if (!ignore && attrib != null) + { + GetFieldNumber(ref fieldNumber, attrib, "Tag"); + GetFieldName(ref name, attrib, "Name"); + GetFieldBoolean(ref isRequired, attrib, "IsRequired"); + GetFieldBoolean(ref isPacked, attrib, "IsPacked"); + GetFieldBoolean(ref overwriteList, attrib, "OverwriteList"); + GetDataFormat(ref dataFormat, attrib, "DataFormat"); + GetFieldBoolean(ref asReferenceHasValue, attrib, "AsReferenceHasValue", false); + + if (asReferenceHasValue) + { + asReferenceHasValue = GetFieldBoolean(ref asReference, attrib, "AsReference", true); + } + GetFieldBoolean(ref dynamicType, attrib, "DynamicType"); + done = tagIsPinned = fieldNumber > 0; // note minAcceptFieldNumber only applies to non-proto + } + + if (!done && partialMembers != null) + { + foreach (AttributeMap ppma in partialMembers) + { + if (ppma.TryGet("MemberName", out object tmp) && (string)tmp == member.Name) + { + GetFieldNumber(ref fieldNumber, ppma, "Tag"); + GetFieldName(ref name, ppma, "Name"); + GetFieldBoolean(ref isRequired, ppma, "IsRequired"); + GetFieldBoolean(ref isPacked, ppma, "IsPacked"); + GetFieldBoolean(ref overwriteList, attrib, "OverwriteList"); + GetDataFormat(ref dataFormat, ppma, "DataFormat"); + GetFieldBoolean(ref asReferenceHasValue, attrib, "AsReferenceHasValue", false); + + if (asReferenceHasValue) + { + asReferenceHasValue = GetFieldBoolean(ref asReference, ppma, "AsReference", true); + } + GetFieldBoolean(ref dynamicType, ppma, "DynamicType"); + if (done = tagIsPinned = fieldNumber > 0) break; // note minAcceptFieldNumber only applies to non-proto + } + } + } + } + + if (!ignore && !done && HasFamily(family, AttributeFamily.DataContractSerialier)) + { + attrib = GetAttribute(attribs, "System.Runtime.Serialization.DataMemberAttribute"); + if (attrib != null) + { + GetFieldNumber(ref fieldNumber, attrib, "Order"); + GetFieldName(ref name, attrib, "Name"); + GetFieldBoolean(ref isRequired, attrib, "IsRequired"); + done = fieldNumber >= minAcceptFieldNumber; + if (done) fieldNumber += dataMemberOffset; // dataMemberOffset only applies to DCS flags, to allow us to "bump" WCF by a notch + } + } + if (!ignore && !done && HasFamily(family, AttributeFamily.XmlSerializer)) + { + attrib = GetAttribute(attribs, "System.Xml.Serialization.XmlElementAttribute"); + if (attrib == null) attrib = GetAttribute(attribs, "System.Xml.Serialization.XmlArrayAttribute"); + GetIgnore(ref ignore, attrib, attribs, "System.Xml.Serialization.XmlIgnoreAttribute"); + if (attrib != null && !ignore) + { + GetFieldNumber(ref fieldNumber, attrib, "Order"); + GetFieldName(ref name, attrib, "ElementName"); + done = fieldNumber >= minAcceptFieldNumber; + } + } + if (!ignore && !done) + { + if (GetAttribute(attribs, "System.NonSerializedAttribute") != null) ignore = true; + } + if (ignore || (fieldNumber < minAcceptFieldNumber && !forced)) return null; + ProtoMemberAttribute result = new ProtoMemberAttribute(fieldNumber, forced || inferByTagName) + { + AsReference = asReference, + AsReferenceHasValue = asReferenceHasValue, + DataFormat = dataFormat, + DynamicType = dynamicType, + IsPacked = isPacked, + OverwriteList = overwriteList, + IsRequired = isRequired, + Name = string.IsNullOrEmpty(name) ? member.Name : name, + Member = member, + BackingMember = backingMember, + TagIsPinned = tagIsPinned + }; + return result; + } + + private ValueMember ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute) + { + MemberInfo member; + if (normalizedAttribute == null || (member = normalizedAttribute.Member) == null) return null; // nix + + Type effectiveType = Helpers.GetMemberType(member); + + + Type itemType = null; + Type defaultType = null; + + // check for list types + ResolveListTypes(model, effectiveType, ref itemType, ref defaultType); + bool ignoreListHandling = false; + // but take it back if it is explicitly excluded + if (itemType != null) + { // looks like a list, but double check for IgnoreListHandling + int idx = model.FindOrAddAuto(effectiveType, false, true, false); + if (idx >= 0 && (ignoreListHandling = model[effectiveType].IgnoreListHandling)) + { + itemType = null; + defaultType = null; + } + } + AttributeMap[] attribs = AttributeMap.Create(model, member, true); + AttributeMap attrib; + + object defaultValue = null; + // implicit zero default + if (model.UseImplicitZeroDefaults) + { + switch (Helpers.GetTypeCode(effectiveType)) + { + case ProtoTypeCode.Boolean: defaultValue = false; break; + case ProtoTypeCode.Decimal: defaultValue = (decimal)0; break; + case ProtoTypeCode.Single: defaultValue = (float)0; break; + case ProtoTypeCode.Double: defaultValue = (double)0; break; + case ProtoTypeCode.Byte: defaultValue = (byte)0; break; + case ProtoTypeCode.Char: defaultValue = (char)0; break; + case ProtoTypeCode.Int16: defaultValue = (short)0; break; + case ProtoTypeCode.Int32: defaultValue = (int)0; break; + case ProtoTypeCode.Int64: defaultValue = (long)0; break; + case ProtoTypeCode.SByte: defaultValue = (sbyte)0; break; + case ProtoTypeCode.UInt16: defaultValue = (ushort)0; break; + case ProtoTypeCode.UInt32: defaultValue = (uint)0; break; + case ProtoTypeCode.UInt64: defaultValue = (ulong)0; break; + case ProtoTypeCode.TimeSpan: defaultValue = TimeSpan.Zero; break; + case ProtoTypeCode.Guid: defaultValue = Guid.Empty; break; + } + } + if ((attrib = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null) + { + if (attrib.TryGet("Value", out object tmp)) defaultValue = tmp; + } + ValueMember vm = ((isEnum || normalizedAttribute.Tag > 0)) + ? new ValueMember(model, type, normalizedAttribute.Tag, member, effectiveType, itemType, defaultType, normalizedAttribute.DataFormat, defaultValue) + : null; + if (vm != null) + { + vm.BackingMember = normalizedAttribute.BackingMember; +#if COREFX || PROFILE259 + TypeInfo finalType = typeInfo; +#else + Type finalType = type; +#endif + PropertyInfo prop = Helpers.GetProperty(finalType, member.Name + "Specified", true); + MethodInfo getMethod = Helpers.GetGetMethod(prop, true, true); + if (getMethod == null || getMethod.IsStatic) prop = null; + if (prop != null) + { + vm.SetSpecified(getMethod, Helpers.GetSetMethod(prop, true, true)); + } + else + { + MethodInfo method = Helpers.GetInstanceMethod(finalType, "ShouldSerialize" + member.Name, Helpers.EmptyTypes); + if (method != null && method.ReturnType == model.MapType(typeof(bool))) + { + vm.SetSpecified(method, null); + } + } + if (!string.IsNullOrEmpty(normalizedAttribute.Name)) vm.SetName(normalizedAttribute.Name); + vm.IsPacked = normalizedAttribute.IsPacked; + vm.IsRequired = normalizedAttribute.IsRequired; + vm.OverwriteList = normalizedAttribute.OverwriteList; + if (normalizedAttribute.AsReferenceHasValue) + { + vm.AsReference = normalizedAttribute.AsReference; + } + vm.DynamicType = normalizedAttribute.DynamicType; + + vm.IsMap = ignoreListHandling ? false : vm.ResolveMapTypes(out var _, out var _, out var _); + if (vm.IsMap) // is it even *allowed* to be a map? + { + if ((attrib = GetAttribute(attribs, "ProtoBuf.ProtoMapAttribute")) != null) + { + if (attrib.TryGet(nameof(ProtoMapAttribute.DisableMap), out object tmp) && (bool)tmp) + { + vm.IsMap = false; + } + else + { + if (attrib.TryGet(nameof(ProtoMapAttribute.KeyFormat), out tmp)) vm.MapKeyFormat = (DataFormat)tmp; + if (attrib.TryGet(nameof(ProtoMapAttribute.ValueFormat), out tmp)) vm.MapValueFormat = (DataFormat)tmp; + } + } + } + + } + return vm; + } + + private static void GetDataFormat(ref DataFormat value, AttributeMap attrib, string memberName) + { + if ((attrib == null) || (value != DataFormat.Default)) return; + if (attrib.TryGet(memberName, out object obj) && obj != null) value = (DataFormat)obj; + } + + private static void GetIgnore(ref bool ignore, AttributeMap attrib, AttributeMap[] attribs, string fullName) + { + if (ignore || attrib == null) return; + ignore = GetAttribute(attribs, fullName) != null; + return; + } + + private static void GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName) + { + GetFieldBoolean(ref value, attrib, memberName, true); + } + private static bool GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName, bool publicOnly) + { + if (attrib == null) return false; + if (value) return true; + if (attrib.TryGet(memberName, publicOnly, out object obj) && obj != null) + { + value = (bool)obj; + return true; + } + return false; + } + + private static void GetFieldNumber(ref int value, AttributeMap attrib, string memberName) + { + if (attrib == null || value > 0) return; + if (attrib.TryGet(memberName, out object obj) && obj != null) value = (int)obj; + } + + private static void GetFieldName(ref string name, AttributeMap attrib, string memberName) + { + if (attrib == null || !string.IsNullOrEmpty(name)) return; + if (attrib.TryGet(memberName, out object obj) && obj != null) name = (string)obj; + } + + private static AttributeMap GetAttribute(AttributeMap[] attribs, string fullName) + { + for (int i = 0; i < attribs.Length; i++) + { + AttributeMap attrib = attribs[i]; + if (attrib != null && attrib.AttributeType.FullName == fullName) return attrib; + } + return null; + } + + /// + /// Adds a member (by name) to the MetaType + /// + public MetaType Add(int fieldNumber, string memberName) + { + AddField(fieldNumber, memberName, null, null, null); + return this; + } + + /// + /// Adds a member (by name) to the MetaType, returning the ValueMember rather than the fluent API. + /// This is otherwise identical to Add. + /// + public ValueMember AddField(int fieldNumber, string memberName) + { + return AddField(fieldNumber, memberName, null, null, null); + } + + /// + /// Gets or sets whether the type should use a parameterless constructor (the default), + /// or whether the type should skip the constructor completely. This option is not supported + /// on compact-framework. + /// + public bool UseConstructor + { // negated to have defaults as flat zero + get { return !HasFlag(OPTIONS_SkipConstructor); } + set { SetFlag(OPTIONS_SkipConstructor, !value, true); } + } + + /// + /// The concrete type to create when a new instance of this type is needed; this may be useful when dealing + /// with dynamic proxies, or with interface-based APIs + /// + public Type ConstructType + { + get { return constructType; } + set + { + ThrowIfFrozen(); + constructType = value; + } + } + + private Type constructType; + /// + /// Adds a member (by name) to the MetaType + /// + public MetaType Add(string memberName) + { + Add(GetNextFieldNumber(), memberName); + return this; + } + + Type surrogate; + /// + /// Performs serialization of this type via a surrogate; all + /// other serialization options are ignored and handled + /// by the surrogate's configuration. + /// + public void SetSurrogate(Type surrogateType) + { + if (surrogateType == type) surrogateType = null; + if (surrogateType != null) + { + // note that BuildSerializer checks the **CURRENT TYPE** is OK to be surrogated + if (surrogateType != null && Helpers.IsAssignableFrom(model.MapType(typeof(IEnumerable)), surrogateType)) + { + throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a surrogate"); + } + } + ThrowIfFrozen(); + this.surrogate = surrogateType; + // no point in offering chaining; no options are respected + } + + internal MetaType GetSurrogateOrSelf() + { + if (surrogate != null) return model[surrogate]; + return this; + } + + internal MetaType GetSurrogateOrBaseOrSelf(bool deep) + { + if (surrogate != null) return model[surrogate]; + MetaType snapshot = this.baseType; + if (snapshot != null) + { + if (deep) + { + MetaType tmp; + do + { + tmp = snapshot; + snapshot = snapshot.baseType; + } while (snapshot != null); + return tmp; + } + return snapshot; + } + return this; + } + + private int GetNextFieldNumber() + { + int maxField = 0; + foreach (ValueMember member in fields) + { + if (member.FieldNumber > maxField) maxField = member.FieldNumber; + } + if (subTypes != null) + { + foreach (SubType subType in subTypes) + { + if (subType.FieldNumber > maxField) maxField = subType.FieldNumber; + } + } + return maxField + 1; + } + + /// + /// Adds a set of members (by name) to the MetaType + /// + public MetaType Add(params string[] memberNames) + { + if (memberNames == null) throw new ArgumentNullException("memberNames"); + int next = GetNextFieldNumber(); + for (int i = 0; i < memberNames.Length; i++) + { + Add(next++, memberNames[i]); + } + return this; + } + + /// + /// Adds a member (by name) to the MetaType + /// + public MetaType Add(int fieldNumber, string memberName, object defaultValue) + { + AddField(fieldNumber, memberName, null, null, defaultValue); + return this; + } + + /// + /// Adds a member (by name) to the MetaType, including an itemType and defaultType for representing lists + /// + public MetaType Add(int fieldNumber, string memberName, Type itemType, Type defaultType) + { + AddField(fieldNumber, memberName, itemType, defaultType, null); + return this; + } + + /// + /// Adds a member (by name) to the MetaType, including an itemType and defaultType for representing lists, returning the ValueMember rather than the fluent API. + /// This is otherwise identical to Add. + /// + public ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType) + { + return AddField(fieldNumber, memberName, itemType, defaultType, null); + } + + private ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType, object defaultValue) + { + MemberInfo mi = null; +#if PROFILE259 + mi = Helpers.IsEnum(type) ? type.GetTypeInfo().GetDeclaredField(memberName) : Helpers.GetInstanceMember(type.GetTypeInfo(), memberName); + +#else + MemberInfo[] members = type.GetMember(memberName, Helpers.IsEnum(type) ? BindingFlags.Static | BindingFlags.Public : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (members != null && members.Length == 1) mi = members[0]; +#endif + if (mi == null) throw new ArgumentException("Unable to determine member: " + memberName, "memberName"); + + Type miType; + PropertyInfo pi = null; + FieldInfo fi = null; +#if PORTABLE || COREFX || PROFILE259 + pi = mi as PropertyInfo; + if (pi == null) + { + fi = mi as FieldInfo; + if (fi == null) + { + throw new NotSupportedException(mi.GetType().Name); + } + else + { + miType = fi.FieldType; + } + } + else + { + miType = pi.PropertyType; + } +#else + switch (mi.MemberType) + { + case MemberTypes.Field: + fi = (FieldInfo)mi; + miType = fi.FieldType; break; + case MemberTypes.Property: + pi = (PropertyInfo)mi; + miType = pi.PropertyType; break; + default: + throw new NotSupportedException(mi.MemberType.ToString()); + } +#endif + ResolveListTypes(model, miType, ref itemType, ref defaultType); + + MemberInfo backingField = null; + if (pi?.CanWrite == false) + { + string name = $"<{((PropertyInfo)mi).Name}>k__BackingField"; +#if PROFILE259 + var backingMembers = type.GetTypeInfo().DeclaredMembers; + var memberInfos = backingMembers as MemberInfo[] ?? backingMembers.ToArray(); + if (memberInfos.Count() == 1) + { + MemberInfo first = memberInfos.FirstOrDefault(); + if (first is FieldInfo) + { + backingField = first; + } + } +#else + var backingMembers = type.GetMember($"<{((PropertyInfo)mi).Name}>k__BackingField", Helpers.IsEnum(type) ? BindingFlags.Static | BindingFlags.Public : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (backingMembers != null && backingMembers.Length == 1 && (backingMembers[0] as FieldInfo) != null) + backingField = backingMembers[0]; +#endif + } + ValueMember newField = new ValueMember(model, type, fieldNumber, backingField ?? mi, miType, itemType, defaultType, DataFormat.Default, defaultValue); + if (backingField != null) + newField.SetName(mi.Name); + Add(newField); + return newField; + } + + internal static void ResolveListTypes(TypeModel model, Type type, ref Type itemType, ref Type defaultType) + { + if (type == null) return; + // handle arrays + if (type.IsArray) + { + if (type.GetArrayRank() != 1) + { + throw new NotSupportedException("Multi-dimensional arrays are not supported"); + } + itemType = type.GetElementType(); + if (itemType == model.MapType(typeof(byte))) + { + defaultType = itemType = null; + } + else + { + defaultType = type; + } + } + // handle lists + if (itemType == null) { itemType = TypeModel.GetListItemType(model, type); } + + // check for nested data (not allowed) + if (itemType != null) + { + Type nestedItemType = null, nestedDefaultType = null; + ResolveListTypes(model, itemType, ref nestedItemType, ref nestedDefaultType); + if (nestedItemType != null) + { + throw TypeModel.CreateNestedListsNotSupported(type); + } + } + + if (itemType != null && defaultType == null) + { +#if COREFX || PROFILE259 + TypeInfo typeInfo = type.GetTypeInfo(); + if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null) +#else + if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null) +#endif + { + defaultType = type; + } + if (defaultType == null) + { +#if COREFX || PROFILE259 + if (typeInfo.IsInterface) +#else + if (type.IsInterface) +#endif + { + + Type[] genArgs; +#if COREFX || PROFILE259 + if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>) + && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments)) +#else + if (type.IsGenericType && type.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.IDictionary<,>)) + && itemType == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments())) +#endif + { + defaultType = model.MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs); + } + else + { + defaultType = model.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType); + } + } + } + // verify that the default type is appropriate + if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; } + } + } + + private void Add(ValueMember member) + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + ThrowIfFrozen(); + fields.Add(member); + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + /// + /// Returns the ValueMember that matchs a given field number, or null if not found + /// + public ValueMember this[int fieldNumber] + { + get + { + foreach (ValueMember member in fields) + { + if (member.FieldNumber == fieldNumber) return member; + } + return null; + } + } + /// + /// Returns the ValueMember that matchs a given member (property/field), or null if not found + /// + public ValueMember this[MemberInfo member] + { + get + { + if (member == null) return null; + foreach (ValueMember x in fields) + { + if (x.Member == member || x.BackingMember == member) return x; + } + return null; + } + } + private readonly BasicList fields = new BasicList(); + + /// + /// Returns the ValueMember instances associated with this type + /// + public ValueMember[] GetFields() + { + ValueMember[] arr = new ValueMember[fields.Count]; + fields.CopyTo(arr, 0); + Array.Sort(arr, ValueMember.Comparer.Default); + return arr; + } + + /// + /// Returns the SubType instances associated with this type + /// + public SubType[] GetSubtypes() + { + if (subTypes == null || subTypes.Count == 0) return new SubType[0]; + SubType[] arr = new SubType[subTypes.Count]; + subTypes.CopyTo(arr, 0); + Array.Sort(arr, SubType.Comparer.Default); + return arr; + } + + internal IEnumerable GetAllGenericArguments() + { + return GetAllGenericArguments(type); + } + + private static IEnumerable GetAllGenericArguments(Type type) + { + +#if PROFILE259 + var genericArguments = type.GetGenericTypeDefinition().GenericTypeArguments; +#else + var genericArguments = type.GetGenericArguments(); +#endif + foreach (var arg in genericArguments) + { + yield return arg; + foreach (var inner in GetAllGenericArguments(arg)) + { + yield return inner; + } + } + } + +#if FEAT_COMPILER + /// + /// Compiles the serializer for this type; this is *not* a full + /// standalone compile, but can significantly boost performance + /// while allowing additional types to be added. + /// + /// An in-place compile can access non-public types / members + public void CompileInPlace() + { + serializer = CompiledSerializer.Wrap(Serializer, model); + } +#endif + + internal bool IsDefined(int fieldNumber) + { + foreach (ValueMember field in fields) + { + if (field.FieldNumber == fieldNumber) return true; + } + return false; + } + + internal int GetKey(bool demand, bool getBaseKey) + { + return model.GetKey(type, demand, getBaseKey); + } + + internal EnumSerializer.EnumPair[] GetEnumMap() + { + if (HasFlag(OPTIONS_EnumPassThru)) return null; + EnumSerializer.EnumPair[] result = new EnumSerializer.EnumPair[fields.Count]; + for (int i = 0; i < result.Length; i++) + { + ValueMember member = (ValueMember)fields[i]; + int wireValue = member.FieldNumber; + object value = member.GetRawEnumValue(); + result[i] = new EnumSerializer.EnumPair(wireValue, value, member.MemberType); + } + return result; + } + + /// + /// Gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather + /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums. + /// + public bool EnumPassthru + { + get { return HasFlag(OPTIONS_EnumPassThru); } + set { SetFlag(OPTIONS_EnumPassThru, value, true); } + } + + /// + /// Gets or sets a value indicating that this type should NOT be treated as a list, even if it has + /// familiar list-like characteristics (enumerable, add, etc) + /// + public bool IgnoreListHandling + { + get { return HasFlag(OPTIONS_IgnoreListHandling); } + set { SetFlag(OPTIONS_IgnoreListHandling, value, true); } + } + + internal bool Pending + { + get { return HasFlag(OPTIONS_Pending); } + set { SetFlag(OPTIONS_Pending, value, false); } + } + + private const ushort + OPTIONS_Pending = 1, + OPTIONS_EnumPassThru = 2, + OPTIONS_Frozen = 4, + OPTIONS_PrivateOnApi = 8, + OPTIONS_SkipConstructor = 16, + OPTIONS_AsReferenceDefault = 32, + OPTIONS_AutoTuple = 64, + OPTIONS_IgnoreListHandling = 128, + OPTIONS_IsGroup = 256; + + private volatile ushort flags; + private bool HasFlag(ushort flag) { return (flags & flag) == flag; } + private void SetFlag(ushort flag, bool value, bool throwIfFrozen) + { + if (throwIfFrozen && HasFlag(flag) != value) + { + ThrowIfFrozen(); + } + if (value) + flags |= flag; + else + flags = (ushort)(flags & ~flag); + } + + internal static MetaType GetRootType(MetaType source) + { + while (source.serializer != null) + { + MetaType tmp = source.baseType; + if (tmp == null) return source; + source = tmp; // else loop until we reach something that isn't generated, or is the root + } + + // now we get into uncertain territory + RuntimeTypeModel model = source.model; + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + + MetaType tmp; + while ((tmp = source.baseType) != null) source = tmp; + return source; + + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + internal bool IsPrepared() + { +#if FEAT_COMPILER + return serializer is CompiledSerializer; +#else + return false; +#endif + } + + internal IEnumerable Fields => this.fields; + + internal static StringBuilder NewLine(StringBuilder builder, int indent) + { + return Helpers.AppendLine(builder).Append(' ', indent * 3); + } + + internal bool IsAutoTuple => HasFlag(OPTIONS_AutoTuple); + + /// + /// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message) + /// + public bool IsGroup + { + get { return HasFlag(OPTIONS_IsGroup); } + set { SetFlag(OPTIONS_IsGroup, value, true); } + } + + internal void WriteSchema(StringBuilder builder, int indent, ref RuntimeTypeModel.CommonImports imports, ProtoSyntax syntax) + { + if (surrogate != null) return; // nothing to write + + ValueMember[] fieldsArr = new ValueMember[fields.Count]; + fields.CopyTo(fieldsArr, 0); + Array.Sort(fieldsArr, ValueMember.Comparer.Default); + + if (IsList) + { + string itemTypeName = model.GetSchemaTypeName(TypeModel.GetListItemType(model, type), DataFormat.Default, false, false, ref imports); + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + NewLine(builder, indent + 1).Append("repeated ").Append(itemTypeName).Append(" items = 1;"); + NewLine(builder, indent).Append('}'); + } + else if (IsAutoTuple) + { // key-value-pair etc + + if (ResolveTupleConstructor(type, out MemberInfo[] mapping) != null) + { + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + for (int i = 0; i < mapping.Length; i++) + { + Type effectiveType; + if (mapping[i] is PropertyInfo property) + { + effectiveType = property.PropertyType; + } + else if (mapping[i] is FieldInfo field) + { + effectiveType = field.FieldType; + } + else + { + throw new NotSupportedException("Unknown member type: " + mapping[i].GetType().Name); + } + NewLine(builder, indent + 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(model.GetSchemaTypeName(effectiveType, DataFormat.Default, false, false, ref imports).Replace('.', '_')) + .Append(' ').Append(mapping[i].Name).Append(" = ").Append(i + 1).Append(';'); + } + NewLine(builder, indent).Append('}'); + } + } + else if (Helpers.IsEnum(type)) + { + NewLine(builder, indent).Append("enum ").Append(GetSchemaTypeName()).Append(" {"); + if (fieldsArr.Length == 0 && EnumPassthru) + { + if (type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif +.IsDefined(model.MapType(typeof(FlagsAttribute)), false)) + { + NewLine(builder, indent + 1).Append("// this is a composite/flags enumeration"); + } + else + { + NewLine(builder, indent + 1).Append("// this enumeration will be passed as a raw value"); + } + foreach (FieldInfo field in +#if PROFILE259 + type.GetRuntimeFields() +#else + type.GetFields() +#endif + + ) + { + if (field.IsStatic && field.IsLiteral) + { + object enumVal; +#if PORTABLE || CF || NETSTANDARD1_3 || NETSTANDARD1_4 || PROFILE259 || UAP + enumVal = Convert.ChangeType(field.GetValue(null), Enum.GetUnderlyingType(field.FieldType), System.Globalization.CultureInfo.InvariantCulture); +#else + enumVal = field.GetRawConstantValue(); +#endif + NewLine(builder, indent + 1).Append(field.Name).Append(" = ").Append(enumVal).Append(";"); + } + } + + } + else + { + Dictionary countByField = new Dictionary(fieldsArr.Length); + bool needsAlias = false; + foreach (var field in fieldsArr) + { + if (countByField.ContainsKey(field.FieldNumber)) + { // no point actually counting; that's enough to know we have a problem + needsAlias = true; + break; + } + countByField.Add(field.FieldNumber, 1); + } + if (needsAlias) + { // duplicated value requires allow_alias + NewLine(builder, indent + 1).Append("option allow_alias = true;"); + } + + bool haveWrittenZero = false; + // write zero values **first** + foreach (ValueMember member in fieldsArr) + { + if (member.FieldNumber == 0) + { + NewLine(builder, indent + 1).Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(';'); + haveWrittenZero = true; + } + } + if (syntax == ProtoSyntax.Proto3 && !haveWrittenZero) + { + NewLine(builder, indent + 1).Append("ZERO = 0; // proto3 requires a zero value as the first item (it can be named anything)"); + } + // note array is already sorted, so zero would already be first + foreach (ValueMember member in fieldsArr) + { + if (member.FieldNumber == 0) continue; + NewLine(builder, indent + 1).Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(';'); + } + } + NewLine(builder, indent).Append('}'); + } + else + { + NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName()).Append(" {"); + foreach (ValueMember member in fieldsArr) + { + string schemaTypeName; + bool hasOption = false; + if (member.IsMap) + { + member.ResolveMapTypes(out var _, out var keyType, out var valueType); + + var keyTypeName = model.GetSchemaTypeName(keyType, member.MapKeyFormat, false, false, ref imports); + schemaTypeName = model.GetSchemaTypeName(valueType, member.MapKeyFormat, member.AsReference, member.DynamicType, ref imports); + NewLine(builder, indent + 1).Append("map<").Append(keyTypeName).Append(",").Append(schemaTypeName).Append("> ") + .Append(member.Name).Append(" = ").Append(member.FieldNumber).Append(";"); + } + else + { + string ordinality = member.ItemType != null ? "repeated " : (syntax == ProtoSyntax.Proto2 ? (member.IsRequired ? "required " : "optional ") : ""); + NewLine(builder, indent + 1).Append(ordinality); + if (member.DataFormat == DataFormat.Group) builder.Append("group "); + schemaTypeName = member.GetSchemaTypeName(true, ref imports); + builder.Append(schemaTypeName).Append(" ") + .Append(member.Name).Append(" = ").Append(member.FieldNumber); + + if (syntax == ProtoSyntax.Proto2 && member.DefaultValue != null && member.IsRequired == false) + { + if (member.DefaultValue is string) + { + AddOption(builder, ref hasOption).Append("default = \"").Append(member.DefaultValue).Append("\""); + } + else if (member.DefaultValue is TimeSpan) + { + // ignore + } + else if (member.DefaultValue is bool) + { // need to be lower case (issue 304) + AddOption(builder, ref hasOption).Append((bool)member.DefaultValue ? "default = true" : "default = false"); + } + else + { + AddOption(builder, ref hasOption).Append("default = ").Append(member.DefaultValue); + } + } + if (CanPack(member.ItemType)) + { + if (syntax == ProtoSyntax.Proto2) + { + if (member.IsPacked) AddOption(builder, ref hasOption).Append("packed = true"); // disabled by default + } + else + { + if (!member.IsPacked) AddOption(builder, ref hasOption).Append("packed = false"); // enabled by default + } + } + if (member.AsReference) + { + imports |= RuntimeTypeModel.CommonImports.Protogen; + AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).asRef = true"); + } + if (member.DynamicType) + { + imports |= RuntimeTypeModel.CommonImports.Protogen; + AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).dynamicType = true"); + } + CloseOption(builder, ref hasOption).Append(';'); + if (syntax != ProtoSyntax.Proto2 && member.DefaultValue != null && !member.IsRequired) + { + if (IsImplicitDefault(member.DefaultValue)) + { + // don't emit; we're good + } + else + { + builder.Append(" // default value could not be applied: ").Append(member.DefaultValue); + } + } + } + if (schemaTypeName == ".bcl.NetObjectProxy" && member.AsReference && !member.DynamicType) // we know what it is; tell the user + { + builder.Append(" // reference-tracked ").Append(member.GetSchemaTypeName(false, ref imports)); + } + } + if (subTypes != null && subTypes.Count != 0) + { + SubType[] subTypeArr = new SubType[subTypes.Count]; + subTypes.CopyTo(subTypeArr, 0); + Array.Sort(subTypeArr, SubType.Comparer.Default); + string[] fieldNames = new string[subTypeArr.Length]; + for(int i = 0; i < subTypeArr.Length;i++) + fieldNames[i] = subTypeArr[i].DerivedType.GetSchemaTypeName(); + + string fieldName = "subtype"; + while (Array.IndexOf(fieldNames, fieldName) >= 0) + fieldName = "_" + fieldName; + + NewLine(builder, indent + 1).Append("oneof ").Append(fieldName).Append(" {"); + for(int i = 0; i < subTypeArr.Length; i++) + { + var subTypeName = fieldNames[i]; + NewLine(builder, indent + 2).Append(subTypeName) + .Append(" ").Append(subTypeName).Append(" = ").Append(subTypeArr[i].FieldNumber).Append(';'); + } + NewLine(builder, indent + 1).Append("}"); + } + NewLine(builder, indent).Append('}'); + } + } + + private static StringBuilder AddOption(StringBuilder builder, ref bool hasOption) + { + if (hasOption) + return builder.Append(", "); + hasOption = true; + return builder.Append(" ["); + } + + private static StringBuilder CloseOption(StringBuilder builder, ref bool hasOption) + { + if (hasOption) + { + hasOption = false; + return builder.Append("]"); + } + return builder; + } + + private static bool IsImplicitDefault(object value) + { + try + { + if (value == null) return false; + switch (Helpers.GetTypeCode(value.GetType())) + { + case ProtoTypeCode.Boolean: return ((bool)value) == false; + case ProtoTypeCode.Byte: return ((byte)value) == (byte)0; + case ProtoTypeCode.Char: return ((char)value) == (char)0; + case ProtoTypeCode.DateTime: return ((DateTime)value) == default; + case ProtoTypeCode.Decimal: return ((decimal)value) == 0M; + case ProtoTypeCode.Double: return ((double)value) == (double)0; + case ProtoTypeCode.Int16: return ((short)value) == (short)0; + case ProtoTypeCode.Int32: return ((int)value) == (int)0; + case ProtoTypeCode.Int64: return ((long)value) == (long)0; + case ProtoTypeCode.SByte: return ((sbyte)value) == (sbyte)0; + case ProtoTypeCode.Single: return ((float)value) == (float)0; + case ProtoTypeCode.String: return ((string)value) == ""; + case ProtoTypeCode.TimeSpan: return ((TimeSpan)value) == TimeSpan.Zero; + case ProtoTypeCode.UInt16: return ((ushort)value) == (ushort)0; + case ProtoTypeCode.UInt32: return ((uint)value) == (uint)0; + case ProtoTypeCode.UInt64: return ((ulong)value) == (ulong)0; + } + } + catch { } + return false; + } + + private static bool CanPack(Type type) + { + if (type == null) return false; + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.Double: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.Int64: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Single: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.UInt64: + return true; + } + return false; + } + + /// + /// Apply a shift to all fields (and sub-types) on this type + /// + /// The change in field number to apply + /// The resultant field numbers must still all be considered valid +#if !(NETSTANDARD1_0 || NETSTANDARD1_3 || UAP) + [System.ComponentModel.Browsable(false)] +#endif + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + public void ApplyFieldOffset(int offset) + { + if (Helpers.IsEnum(type)) throw new InvalidOperationException("Cannot apply field-offset to an enum"); + if (offset == 0) return; // nothing to do + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken); + ThrowIfFrozen(); + + if (fields != null) + { + foreach(ValueMember field in fields) + AssertValidFieldNumber(field.FieldNumber + offset); + } + if (subTypes != null) + { + foreach (SubType subType in subTypes) + AssertValidFieldNumber(subType.FieldNumber + offset); + } + + // we've checked the ranges are all OK; since we're moving everything, we can't overlap ourselves + // so: we can just move + if (fields != null) + { + foreach (ValueMember field in fields) + field.FieldNumber += offset; + } + if (subTypes != null) + { + foreach (SubType subType in subTypes) + subType.FieldNumber += offset; + } + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + internal static void AssertValidFieldNumber(int fieldNumber) + { + if (fieldNumber < 1) throw new ArgumentOutOfRangeException(nameof(fieldNumber)); + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/MetaType.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/MetaType.cs.meta new file mode 100644 index 00000000..edc2cad7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/MetaType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 170c607ac9d3b9346a8f4197e9e4d86a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs new file mode 100644 index 00000000..ab90d5b8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs @@ -0,0 +1,17 @@ +namespace ProtoBuf.Meta +{ + /// + /// Indiate the variant of the protobuf .proto DSL syntax to use + /// + public enum ProtoSyntax + { + /// + /// https://developers.google.com/protocol-buffers/docs/proto + /// + Proto2 = 0, + /// + /// https://developers.google.com/protocol-buffers/docs/proto3 + /// + Proto3 = 1, + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta new file mode 100644 index 00000000..23200250 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ProtoSyntax.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8df2b30e0bc1f274a8170e86c9d08f96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs new file mode 100644 index 00000000..05dfcf18 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs @@ -0,0 +1,2036 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Text; +using System.Reflection; +#if FEAT_COMPILER +using System.Reflection.Emit; +#endif + +using ProtoBuf.Serializers; +using System.Threading; +using System.IO; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace ProtoBuf.Meta +{ + /// + /// Provides protobuf serialization support for a number of types that can be defined at runtime + /// + public sealed class RuntimeTypeModel : TypeModel + { + private ushort options; + private const ushort + OPTIONS_InferTagFromNameDefault = 1, + OPTIONS_IsDefaultModel = 2, + OPTIONS_Frozen = 4, + OPTIONS_AutoAddMissingTypes = 8, +#if FEAT_COMPILER + OPTIONS_AutoCompile = 16, +#endif + OPTIONS_UseImplicitZeroDefaults = 32, + OPTIONS_AllowParseableTypes = 64, + OPTIONS_AutoAddProtoContractTypesOnly = 128, + OPTIONS_IncludeDateTimeKind = 256, + OPTIONS_DoNotInternStrings = 512; + + private bool GetOption(ushort option) + { + return (options & option) == option; + } + + private void SetOption(ushort option, bool value) + { + if (value) options |= option; + else options &= (ushort)~option; + } + + /// + /// Global default that + /// enables/disables automatic tag generation based on the existing name / order + /// of the defined members. See + /// for usage and important warning / explanation. + /// You must set the global default before attempting to serialize/deserialize any + /// impacted type. + /// + public bool InferTagFromNameDefault + { + get { return GetOption(OPTIONS_InferTagFromNameDefault); } + set { SetOption(OPTIONS_InferTagFromNameDefault, value); } + } + + /// + /// Global default that determines whether types are considered serializable + /// if they have [DataContract] / [XmlType]. With this enabled, ONLY + /// types marked as [ProtoContract] are added automatically. + /// + public bool AutoAddProtoContractTypesOnly + { + get { return GetOption(OPTIONS_AutoAddProtoContractTypesOnly); } + set { SetOption(OPTIONS_AutoAddProtoContractTypesOnly, value); } + } + + /// + /// Global switch that enables or disables the implicit + /// handling of "zero defaults"; meanning: if no other default is specified, + /// it assumes bools always default to false, integers to zero, etc. + /// + /// If this is disabled, no such assumptions are made and only *explicit* + /// default values are processed. This is enabled by default to + /// preserve similar logic to v1. + /// + public bool UseImplicitZeroDefaults + { + get { return GetOption(OPTIONS_UseImplicitZeroDefaults); } + set + { + if (!value && GetOption(OPTIONS_IsDefaultModel)) + { + throw new InvalidOperationException("UseImplicitZeroDefaults cannot be disabled on the default model"); + } + SetOption(OPTIONS_UseImplicitZeroDefaults, value); + } + } + + /// + /// Global switch that determines whether types with a .ToString() and a Parse(string) + /// should be serialized as strings. + /// + public bool AllowParseableTypes + { + get { return GetOption(OPTIONS_AllowParseableTypes); } + set { SetOption(OPTIONS_AllowParseableTypes, value); } + } + + /// + /// Global switch that determines whether DateTime serialization should include the Kind of the date/time. + /// + public bool IncludeDateTimeKind + { + get { return GetOption(OPTIONS_IncludeDateTimeKind); } + set { SetOption(OPTIONS_IncludeDateTimeKind, value); } + } + + /// + /// Global switch that determines whether a single instance of the same string should be used during deserialization. + /// + /// Note this does not use the global .NET string interner + public bool InternStrings + { + get { return !GetOption(OPTIONS_DoNotInternStrings); } + set { SetOption(OPTIONS_DoNotInternStrings, !value); } + } + + /// + /// Should the Kind be included on date/time values? + /// + protected internal override bool SerializeDateTimeKind() + { + return GetOption(OPTIONS_IncludeDateTimeKind); + } + + private sealed class Singleton + { + private Singleton() { } + internal static readonly RuntimeTypeModel Value = new RuntimeTypeModel(true); + } + + /// + /// The default model, used to support ProtoBuf.Serializer + /// + public static RuntimeTypeModel Default => Singleton.Value; + + /// + /// Returns a sequence of the Type instances that can be + /// processed by this model. + /// + public IEnumerable GetTypes() => types; + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for, or null to generate a .proto that represents the entire model + /// The .proto definition as a string + /// The .proto syntax to use + public override string GetSchema(Type type, ProtoSyntax syntax) + { + BasicList requiredTypes = new BasicList(); + MetaType primaryType = null; + bool isInbuiltType = false; + if (type == null) + { // generate for the entire model + foreach (MetaType meta in types) + { + MetaType tmp = meta.GetSurrogateOrBaseOrSelf(false); + if (!requiredTypes.Contains(tmp)) + { // ^^^ note that the type might have been added as a descendent + requiredTypes.Add(tmp); + CascadeDependents(requiredTypes, tmp); + } + } + } + else + { + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + + WireType defaultWireType; + isInbuiltType = (ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out defaultWireType, false, false, false, false) != null); + if (!isInbuiltType) + { + //Agenerate just relative to the supplied type + int index = FindOrAddAuto(type, false, false, false); + if (index < 0) throw new ArgumentException("The type specified is not a contract-type", "type"); + + // get the required types + primaryType = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false); + requiredTypes.Add(primaryType); + CascadeDependents(requiredTypes, primaryType); + } + } + + // use the provided type's namespace for the "package" + StringBuilder headerBuilder = new StringBuilder(); + string package = null; + + if (!isInbuiltType) + { + IEnumerable typesForNamespace = primaryType == null ? types : requiredTypes; + foreach (MetaType meta in typesForNamespace) + { + if (meta.IsList) continue; + string tmp = meta.Type.Namespace; + if (!string.IsNullOrEmpty(tmp)) + { + if (tmp.StartsWith("System.")) continue; + if (package == null) + { // haven't seen any suggestions yet + package = tmp; + } + else if (package == tmp) + { // that's fine; a repeat of the one we already saw + } + else + { // something else; have confliucting suggestions; abort + package = null; + break; + } + } + } + } + switch (syntax) + { + case ProtoSyntax.Proto2: + headerBuilder.AppendLine(@"syntax = ""proto2"";"); + break; + case ProtoSyntax.Proto3: + headerBuilder.AppendLine(@"syntax = ""proto3"";"); + break; + default: + throw new ArgumentOutOfRangeException(nameof(syntax)); + } + + if (!string.IsNullOrEmpty(package)) + { + headerBuilder.Append("package ").Append(package).Append(';'); + Helpers.AppendLine(headerBuilder); + } + + var imports = CommonImports.None; + StringBuilder bodyBuilder = new StringBuilder(); + // sort them by schema-name + MetaType[] metaTypesArr = new MetaType[requiredTypes.Count]; + requiredTypes.CopyTo(metaTypesArr, 0); + Array.Sort(metaTypesArr, MetaType.Comparer.Default); + + // write the messages + if (isInbuiltType) + { + Helpers.AppendLine(bodyBuilder).Append("message ").Append(type.Name).Append(" {"); + MetaType.NewLine(bodyBuilder, 1).Append(syntax == ProtoSyntax.Proto2 ? "optional " : "").Append(GetSchemaTypeName(type, DataFormat.Default, false, false, ref imports)) + .Append(" value = 1;"); + Helpers.AppendLine(bodyBuilder).Append('}'); + } + else + { + for (int i = 0; i < metaTypesArr.Length; i++) + { + MetaType tmp = metaTypesArr[i]; + if (tmp.IsList && tmp != primaryType) continue; + tmp.WriteSchema(bodyBuilder, 0, ref imports, syntax); + } + } + if ((imports & CommonImports.Bcl) != 0) + { + headerBuilder.Append("import \"protobuf-net/bcl.proto\"; // schema for protobuf-net's handling of core .NET types"); + Helpers.AppendLine(headerBuilder); + } + if ((imports & CommonImports.Protogen) != 0) + { + headerBuilder.Append("import \"protobuf-net/protogen.proto\"; // custom protobuf-net options"); + Helpers.AppendLine(headerBuilder); + } + if ((imports & CommonImports.Timestamp) != 0) + { + headerBuilder.Append("import \"google/protobuf/timestamp.proto\";"); + Helpers.AppendLine(headerBuilder); + } + if ((imports & CommonImports.Duration) != 0) + { + headerBuilder.Append("import \"google/protobuf/duration.proto\";"); + Helpers.AppendLine(headerBuilder); + } + return Helpers.AppendLine(headerBuilder.Append(bodyBuilder)).ToString(); + } + [Flags] + internal enum CommonImports + { + None = 0, + Bcl = 1, + Timestamp = 2, + Duration = 4, + Protogen = 8 + } + private void CascadeDependents(BasicList list, MetaType metaType) + { + MetaType tmp; + if (metaType.IsList) + { + Type itemType = TypeModel.GetListItemType(this, metaType.Type); + TryGetCoreSerializer(list, itemType); + } + else + { + if (metaType.IsAutoTuple) + { + MemberInfo[] mapping; + if (MetaType.ResolveTupleConstructor(metaType.Type, out mapping) != null) + { + for (int i = 0; i < mapping.Length; i++) + { + Type type = null; + if (mapping[i] is PropertyInfo) type = ((PropertyInfo)mapping[i]).PropertyType; + else if (mapping[i] is FieldInfo) type = ((FieldInfo)mapping[i]).FieldType; + TryGetCoreSerializer(list, type); + } + } + } + else + { + foreach (ValueMember member in metaType.Fields) + { + Type type = member.ItemType; + if (member.IsMap) + { + member.ResolveMapTypes(out _, out _, out type); // don't need key-type + } + if (type == null) type = member.MemberType; + TryGetCoreSerializer(list, type); + } + } + foreach (var genericArgument in metaType.GetAllGenericArguments()) + { + TryGetCoreSerializer(list, genericArgument); + } + if (metaType.HasSubtypes) + { + foreach (SubType subType in metaType.GetSubtypes()) + { + tmp = subType.DerivedType.GetSurrogateOrSelf(); // note: exclude base-types! + if (!list.Contains(tmp)) + { + list.Add(tmp); + CascadeDependents(list, tmp); + } + } + } + tmp = metaType.BaseType; + if (tmp != null) tmp = tmp.GetSurrogateOrSelf(); // note: already walking base-types; exclude base + if (tmp != null && !list.Contains(tmp)) + { + list.Add(tmp); + CascadeDependents(list, tmp); + } + } + } + + private void TryGetCoreSerializer(BasicList list, Type itemType) + { + var coreSerializer = ValueMember.TryGetCoreSerializer(this, DataFormat.Default, itemType, out _, false, false, false, false); + if (coreSerializer != null) + { + return; + } + int index = FindOrAddAuto(itemType, false, false, false); + if (index < 0) + { + return; + } + var temp = ((MetaType)types[index]).GetSurrogateOrBaseOrSelf(false); + if (list.Contains(temp)) + { + return; + } + // could perhaps also implement as a queue, but this should work OK for sane models + list.Add(temp); + CascadeDependents(list, temp); + } + +#if !NO_RUNTIME + /// + /// Creates a new runtime model, to which the caller + /// can add support for a range of types. A model + /// can be used "as is", or can be compiled for + /// optimal performance. + /// + /// not used currently; this is for compatibility with v3 +#pragma warning disable IDE0060 // Remove unused parameter + public static RuntimeTypeModel Create(string name = null) +#pragma warning restore IDE0060 // Remove unused parameter + { + return new RuntimeTypeModel(false); + } +#endif + + private RuntimeTypeModel(bool isDefault) + { + AutoAddMissingTypes = true; + UseImplicitZeroDefaults = true; + SetOption(OPTIONS_IsDefaultModel, isDefault); +#if FEAT_COMPILER && !DEBUG + try + { + AutoCompile = EnableAutoCompile(); + } + catch { } // this is all kinds of brittle on things like UWP +#endif + } + +#if FEAT_COMPILER + [MethodImpl(MethodImplOptions.NoInlining)] + internal static bool EnableAutoCompile() + { + try + { + var dm = new DynamicMethod("CheckCompilerAvailable", typeof(bool), new Type[] { typeof(int) }); + var il = dm.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, 42); + il.Emit(OpCodes.Ceq); + il.Emit(OpCodes.Ret); + var func = (Predicate)dm.CreateDelegate(typeof(Predicate)); + return func(42); + } + catch (Exception ex) + { + Debug.WriteLine(ex); + return false; + } + } +#endif + + /// + /// Obtains the MetaType associated with a given Type for the current model, + /// allowing additional configuration. + /// + public MetaType this[Type type] { get { return (MetaType)types[FindOrAddAuto(type, true, false, false)]; } } + + internal MetaType FindWithoutAdd(Type type) + { + // this list is thread-safe for reading + foreach (MetaType metaType in types) + { + if (metaType.Type == type) + { + if (metaType.Pending) WaitOnLock(metaType); + return metaType; + } + } + // if that failed, check for a proxy + Type underlyingType = ResolveProxies(type); + return underlyingType == null ? null : FindWithoutAdd(underlyingType); + } + + static readonly BasicList.MatchPredicate + MetaTypeFinder = new BasicList.MatchPredicate(MetaTypeFinderImpl), + BasicTypeFinder = new BasicList.MatchPredicate(BasicTypeFinderImpl); + + static bool MetaTypeFinderImpl(object value, object ctx) + { + return ((MetaType)value).Type == (Type)ctx; + } + + static bool BasicTypeFinderImpl(object value, object ctx) + { + return ((BasicType)value).Type == (Type)ctx; + } + + private void WaitOnLock(MetaType type) + { + int opaqueToken = 0; + try + { + TakeLock(ref opaqueToken); + } + finally + { + ReleaseLock(opaqueToken); + } + } + + BasicList basicTypes = new BasicList(); + + sealed class BasicType + { + private readonly Type type; + public Type Type => type; + private readonly IProtoSerializer serializer; + public IProtoSerializer Serializer => serializer; + + public BasicType(Type type, IProtoSerializer serializer) + { + this.type = type; + this.serializer = serializer; + } + } + internal IProtoSerializer TryGetBasicTypeSerializer(Type type) + { + int idx = basicTypes.IndexOf(BasicTypeFinder, type); + + if (idx >= 0) return ((BasicType)basicTypes[idx]).Serializer; + + lock (basicTypes) + { // don't need a full model lock for this + + // double-checked + idx = basicTypes.IndexOf(BasicTypeFinder, type); + if (idx >= 0) return ((BasicType)basicTypes[idx]).Serializer; + + MetaType.AttributeFamily family = MetaType.GetContractFamily(this, type, null); + IProtoSerializer ser = family == MetaType.AttributeFamily.None + ? ValueMember.TryGetCoreSerializer(this, DataFormat.Default, type, out WireType defaultWireType, false, false, false, false) + : null; + + if (ser != null) basicTypes.Add(new BasicType(type, ser)); + return ser; + } + } + + internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled) + { + int key = types.IndexOf(MetaTypeFinder, type); + MetaType metaType; + + // the fast happy path: meta-types we've already seen + if (key >= 0) + { + metaType = (MetaType)types[key]; + if (metaType.Pending) + { + WaitOnLock(metaType); + } + return key; + } + + // the fast fail path: types that will never have a meta-type + bool shouldAdd = AutoAddMissingTypes || addEvenIfAutoDisabled; + + if (!Helpers.IsEnum(type) && TryGetBasicTypeSerializer(type) != null) + { + if (shouldAdd && !addWithContractOnly) throw MetaType.InbuiltType(type); + return -1; // this will never be a meta-type + } + + // otherwise: we don't yet know + + // check for proxy types + Type underlyingType = ResolveProxies(type); + if (underlyingType != null && underlyingType != type) + { + key = types.IndexOf(MetaTypeFinder, underlyingType); + type = underlyingType; // if new added, make it reflect the underlying type + } + + if (key < 0) + { + int opaqueToken = 0; + Type origType = type; + bool weAdded = false; + try + { + TakeLock(ref opaqueToken); + // try to recognise a few familiar patterns... + if ((metaType = RecogniseCommonTypes(type)) == null) + { // otherwise, check if it is a contract + MetaType.AttributeFamily family = MetaType.GetContractFamily(this, type, null); + if (family == MetaType.AttributeFamily.AutoTuple) + { + shouldAdd = addEvenIfAutoDisabled = true; // always add basic tuples, such as KeyValuePair + } + + if (!shouldAdd || ( + !Helpers.IsEnum(type) && addWithContractOnly && family == MetaType.AttributeFamily.None) + ) + { + if (demand) ThrowUnexpectedType(type); + return key; + } + metaType = Create(type); + } + + metaType.Pending = true; + + // double-checked + int winner = types.IndexOf(MetaTypeFinder, type); + if (winner < 0) + { + ThrowIfFrozen(); + key = types.Add(metaType); + weAdded = true; + } + else + { + key = winner; + } + if (weAdded) + { + metaType.ApplyDefaultBehaviour(); + metaType.Pending = false; + } + } + finally + { + ReleaseLock(opaqueToken); + if (weAdded) + { + ResetKeyCache(); + } + } + } + return key; + } + + private MetaType RecogniseCommonTypes(Type type) + { + // if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)) + // { + // MetaType mt = new MetaType(this, type); + + // Type surrogate = typeof (KeyValuePairSurrogate<,>).MakeGenericType(type.GetGenericArguments()); + + // mt.SetSurrogate(surrogate); + // mt.IncludeSerializerMethod = false; + // mt.Freeze(); + + // MetaType surrogateMeta = (MetaType)types[FindOrAddAuto(surrogate, true, true, true)]; // this forcibly adds it if needed + // if(surrogateMeta.IncludeSerializerMethod) + // { // don't blindly set - it might be frozen + // surrogateMeta.IncludeSerializerMethod = false; + // } + // surrogateMeta.Freeze(); + // return mt; + // } + return null; + } + private MetaType Create(Type type) + { + ThrowIfFrozen(); + return new MetaType(this, type, defaultFactory); + } + + /// + /// Adds support for an additional type in this model, optionally + /// applying inbuilt patterns. If the type is already known to the + /// model, the existing type is returned **without** applying + /// any additional behaviour. + /// + /// Inbuilt patterns include: + /// [ProtoContract]/[ProtoMember(n)] + /// [DataContract]/[DataMember(Order=n)] + /// [XmlType]/[XmlElement(Order=n)] + /// [On{Des|S}erializ{ing|ed}] + /// ShouldSerialize*/*Specified + /// + /// The type to be supported + /// Whether to apply the inbuilt configuration patterns (via attributes etc), or + /// just add the type with no additional configuration (the type must then be manually configured). + /// The MetaType representing this type, allowing + /// further configuration. + public MetaType Add(Type type, bool applyDefaultBehaviour) + { + if (type == null) throw new ArgumentNullException("type"); + MetaType newType = FindWithoutAdd(type); + if (newType != null) return newType; // return existing + int opaqueToken = 0; + +#if COREFX || PROFILE259 + TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type); + if (typeInfo.IsInterface && MetaType.ienumerable.IsAssignableFrom(typeInfo) +#else + if (type.IsInterface && MapType(MetaType.ienumerable).IsAssignableFrom(type) +#endif + && GetListItemType(this, type) == null) + { + throw new ArgumentException("IEnumerable[] data cannot be used as a meta-type unless an Add method can be resolved"); + } + try + { + newType = RecogniseCommonTypes(type); + if (newType != null) + { + if (!applyDefaultBehaviour) + { + throw new ArgumentException( + "Default behaviour must be observed for certain types with special handling; " + type.FullName, + "applyDefaultBehaviour"); + } + // we should assume that type is fully configured, though; no need to re-run: + applyDefaultBehaviour = false; + } + if (newType == null) newType = Create(type); + newType.Pending = true; + TakeLock(ref opaqueToken); + // double checked + if (FindWithoutAdd(type) != null) throw new ArgumentException("Duplicate type", "type"); + ThrowIfFrozen(); + types.Add(newType); + if (applyDefaultBehaviour) { newType.ApplyDefaultBehaviour(); } + newType.Pending = false; + } + finally + { + ReleaseLock(opaqueToken); + ResetKeyCache(); + } + + return newType; + } + +#if FEAT_COMPILER + /// + /// Should serializers be compiled on demand? It may be useful + /// to disable this for debugging purposes. + /// + public bool AutoCompile + { + get { return GetOption(OPTIONS_AutoCompile); } + set { SetOption(OPTIONS_AutoCompile, value); } + } +#endif + /// + /// Should support for unexpected types be added automatically? + /// If false, an exception is thrown when unexpected types + /// are encountered. + /// + public bool AutoAddMissingTypes + { + get { return GetOption(OPTIONS_AutoAddMissingTypes); } + set + { + if (!value && GetOption(OPTIONS_IsDefaultModel)) + { + throw new InvalidOperationException("The default model must allow missing types"); + } + ThrowIfFrozen(); + SetOption(OPTIONS_AutoAddMissingTypes, value); + } + } + /// + /// Verifies that the model is still open to changes; if not, an exception is thrown + /// + private void ThrowIfFrozen() + { + if (GetOption(OPTIONS_Frozen)) throw new InvalidOperationException("The model cannot be changed once frozen"); + } + + /// + /// Prevents further changes to this model + /// + public void Freeze() + { + if (GetOption(OPTIONS_IsDefaultModel)) throw new InvalidOperationException("The default model cannot be frozen"); + SetOption(OPTIONS_Frozen, true); + } + + private readonly BasicList types = new BasicList(); + + /// + /// Provides the key that represents a given type in the current model. + /// + protected override int GetKeyImpl(Type type) + { + return GetKey(type, false, true); + } + + internal int GetKey(Type type, bool demand, bool getBaseKey) + { + Helpers.DebugAssert(type != null); + try + { + int typeIndex = FindOrAddAuto(type, demand, true, false); + if (typeIndex >= 0) + { + MetaType mt = (MetaType)types[typeIndex]; + if (getBaseKey) + { + mt = MetaType.GetRootType(mt); + typeIndex = FindOrAddAuto(mt.Type, true, true, false); + } + } + return typeIndex; + } + catch (NotSupportedException) + { + throw; // re-surface "as-is" + } + catch (Exception ex) + { + if (ex.Message.IndexOf(type.FullName) >= 0) throw; // already enough info + throw new ProtoException(ex.Message + " (" + type.FullName + ")", ex); + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + protected internal override void Serialize(int key, object value, ProtoWriter dest) + { + //Helpers.DebugWriteLine("Serialize", value); + ((MetaType)types[key]).Serializer.Write(value, dest); + } + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + protected internal override object Deserialize(int key, object value, ProtoReader source) + { + //Helpers.DebugWriteLine("Deserialize", value); + IProtoSerializer ser = ((MetaType)types[key]).Serializer; + if (value == null && Helpers.IsValueType(ser.ExpectedType)) + { + if (ser.RequiresOldValue) value = Activator.CreateInstance(ser.ExpectedType); + return ser.Read(value, source); + } + else + { + return ser.Read(value, source); + } + } + +#if FEAT_COMPILER + // this is used by some unit-tests; do not remove + internal Compiler.ProtoSerializer GetSerializer(IProtoSerializer serializer, bool compiled) + { + if (serializer == null) throw new ArgumentNullException("serializer"); +#if FEAT_COMPILER + if (compiled) return Compiler.CompilerContext.BuildSerializer(serializer, this); +#endif + return new Compiler.ProtoSerializer(serializer.Write); + } + + /// + /// Compiles the serializers individually; this is *not* a full + /// standalone compile, but can significantly boost performance + /// while allowing additional types to be added. + /// + /// An in-place compile can access non-public types / members + public void CompileInPlace() + { + foreach (MetaType type in types) + { + type.CompileInPlace(); + } + } + +#endif + //internal override IProtoSerializer GetTypeSerializer(Type type) + //{ // this list is thread-safe for reading + // .Serializer; + //} + //internal override IProtoSerializer GetTypeSerializer(int key) + //{ // this list is thread-safe for reading + // MetaType type = (MetaType)types.TryGet(key); + // if (type != null) return type.Serializer; + // throw new KeyNotFoundException(); + + //} + +#if FEAT_COMPILER + private void BuildAllSerializers() + { + // note that types.Count may increase during this operation, as some serializers + // bring other types into play + for (int i = 0; i < types.Count; i++) + { + // the primary purpose of this is to force the creation of the Serializer + MetaType mt = (MetaType)types[i]; + if (mt.Serializer == null) + throw new InvalidOperationException("No serializer available for " + mt.Type.Name); + } + } + + internal sealed class SerializerPair : IComparable + { + int IComparable.CompareTo(object obj) + { + if (obj == null) throw new ArgumentException("obj"); + SerializerPair other = (SerializerPair)obj; + + // we want to bunch all the items with the same base-type together, but we need the items with a + // different base **first**. + if (this.BaseKey == this.MetaKey) + { + if (other.BaseKey == other.MetaKey) + { // neither is a subclass + return this.MetaKey.CompareTo(other.MetaKey); + } + else + { // "other" (only) is involved in inheritance; "other" should be first + return 1; + } + } + else + { + if (other.BaseKey == other.MetaKey) + { // "this" (only) is involved in inheritance; "this" should be first + return -1; + } + else + { // both are involved in inheritance + int result = this.BaseKey.CompareTo(other.BaseKey); + if (result == 0) result = this.MetaKey.CompareTo(other.MetaKey); + return result; + } + } + } + public readonly int MetaKey, BaseKey; + public readonly MetaType Type; + public readonly MethodBuilder Serialize, Deserialize; + public readonly ILGenerator SerializeBody, DeserializeBody; + public SerializerPair(int metaKey, int baseKey, MetaType type, MethodBuilder serialize, MethodBuilder deserialize, + ILGenerator serializeBody, ILGenerator deserializeBody) + { + this.MetaKey = metaKey; + this.BaseKey = baseKey; + this.Serialize = serialize; + this.Deserialize = deserialize; + this.SerializeBody = serializeBody; + this.DeserializeBody = deserializeBody; + this.Type = type; + } + } + + /// + /// Fully compiles the current model into a static-compiled model instance + /// + /// A full compilation is restricted to accessing public types / members + /// An instance of the newly created compiled type-model + public TypeModel Compile() + { + CompilerOptions options = new CompilerOptions(); + return Compile(options); + } + + static ILGenerator Override(TypeBuilder type, string name) + { + MethodInfo baseMethod = type.BaseType.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance); + + ParameterInfo[] parameters = baseMethod.GetParameters(); + Type[] paramTypes = new Type[parameters.Length]; + for (int i = 0; i < paramTypes.Length; i++) + { + paramTypes[i] = parameters[i].ParameterType; + } + MethodBuilder newMethod = type.DefineMethod(baseMethod.Name, + (baseMethod.Attributes & ~MethodAttributes.Abstract) | MethodAttributes.Final, baseMethod.CallingConvention, baseMethod.ReturnType, paramTypes); + ILGenerator il = newMethod.GetILGenerator(); + type.DefineMethodOverride(newMethod, baseMethod); + return il; + } + + /// + /// Represents configuration options for compiling a model to + /// a standalone assembly. + /// + public sealed class CompilerOptions + { + /// + /// Import framework options from an existing type + /// + public void SetFrameworkOptions(MetaType from) + { + if (from == null) throw new ArgumentNullException("from"); + AttributeMap[] attribs = AttributeMap.Create(from.Model, Helpers.GetAssembly(from.Type)); + foreach (AttributeMap attrib in attribs) + { + if (attrib.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute") + { + object tmp; + if (attrib.TryGet("FrameworkName", out tmp)) TargetFrameworkName = (string)tmp; + if (attrib.TryGet("FrameworkDisplayName", out tmp)) TargetFrameworkDisplayName = (string)tmp; + break; + } + } + } + + private string targetFrameworkName, targetFrameworkDisplayName, typeName, outputPath, imageRuntimeVersion; + private int metaDataVersion; + /// + /// The TargetFrameworkAttribute FrameworkName value to burn into the generated assembly + /// + public string TargetFrameworkName { get { return targetFrameworkName; } set { targetFrameworkName = value; } } + + /// + /// The TargetFrameworkAttribute FrameworkDisplayName value to burn into the generated assembly + /// + public string TargetFrameworkDisplayName { get { return targetFrameworkDisplayName; } set { targetFrameworkDisplayName = value; } } + /// + /// The name of the TypeModel class to create + /// + public string TypeName { get { return typeName; } set { typeName = value; } } + +#if COREFX + internal const string NoPersistence = "Assembly persistence not supported on this runtime"; +#endif + /// + /// The path for the new dll + /// +#if COREFX + [Obsolete(NoPersistence)] +#endif + public string OutputPath { get { return outputPath; } set { outputPath = value; } } + /// + /// The runtime version for the generated assembly + /// + public string ImageRuntimeVersion { get { return imageRuntimeVersion; } set { imageRuntimeVersion = value; } } + /// + /// The runtime version for the generated assembly + /// + public int MetaDataVersion { get { return metaDataVersion; } set { metaDataVersion = value; } } + + + private Accessibility accessibility = Accessibility.Public; + /// + /// The acecssibility of the generated serializer + /// + public Accessibility Accessibility { get { return accessibility; } set { accessibility = value; } } + } + + /// + /// Type accessibility + /// + public enum Accessibility + { + /// + /// Available to all callers + /// + Public, + /// + /// Available to all callers in the same assembly, or assemblies specified via [InternalsVisibleTo(...)] + /// + Internal + } + +#if !COREFX + /// + /// Fully compiles the current model into a static-compiled serialization dll + /// (the serialization dll still requires protobuf-net for support services). + /// + /// A full compilation is restricted to accessing public types / members + /// The name of the TypeModel class to create + /// The path for the new dll + /// An instance of the newly created compiled type-model + public TypeModel Compile(string name, string path) + { + CompilerOptions options = new CompilerOptions(); + options.TypeName = name; + options.OutputPath = path; + return Compile(options); + } +#endif + /// + /// Fully compiles the current model into a static-compiled serialization dll + /// (the serialization dll still requires protobuf-net for support services). + /// + /// A full compilation is restricted to accessing public types / members + /// An instance of the newly created compiled type-model + public TypeModel Compile(CompilerOptions options) + { + if (options == null) throw new ArgumentNullException("options"); + string typeName = options.TypeName; +#pragma warning disable 0618 + string path = options.OutputPath; +#pragma warning restore 0618 + BuildAllSerializers(); + Freeze(); + bool save = !string.IsNullOrEmpty(path); + if (string.IsNullOrEmpty(typeName)) + { + if (save) throw new ArgumentNullException("typeName"); + typeName = Guid.NewGuid().ToString(); + } + + + string assemblyName, moduleName; + if (path == null) + { + assemblyName = typeName; + moduleName = assemblyName + ".dll"; + } + else + { + assemblyName = new System.IO.FileInfo(System.IO.Path.GetFileNameWithoutExtension(path)).Name; + moduleName = assemblyName + System.IO.Path.GetExtension(path); + } + +#if COREFX + AssemblyName an = new AssemblyName(); + an.Name = assemblyName; + AssemblyBuilder asm = AssemblyBuilder.DefineDynamicAssembly(an, + AssemblyBuilderAccess.Run); + ModuleBuilder module = asm.DefineDynamicModule(moduleName); +#else + AssemblyName an = new AssemblyName(); + an.Name = assemblyName; + AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(an, + (save ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run) + ); + ModuleBuilder module = save ? asm.DefineDynamicModule(moduleName, path) + : asm.DefineDynamicModule(moduleName); +#endif + + WriteAssemblyAttributes(options, assemblyName, asm); + + TypeBuilder type = WriteBasicTypeModel(options, typeName, module); + + int index; + bool hasInheritance; + SerializerPair[] methodPairs; + Compiler.CompilerContext.ILVersion ilVersion; + WriteSerializers(options, assemblyName, type, out index, out hasInheritance, out methodPairs, out ilVersion); + + ILGenerator il; + int knownTypesCategory; + FieldBuilder knownTypes; + Type knownTypesLookupType; + WriteGetKeyImpl(type, hasInheritance, methodPairs, ilVersion, assemblyName, out il, out knownTypesCategory, out knownTypes, out knownTypesLookupType); + + // trivial flags + il = Override(type, "SerializeDateTimeKind"); + il.Emit(IncludeDateTimeKind ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Ret); + // end: trivial flags + + Compiler.CompilerContext ctx = WriteSerializeDeserialize(assemblyName, type, methodPairs, ilVersion, ref il); + + WriteConstructors(type, ref index, methodPairs, ref il, knownTypesCategory, knownTypes, knownTypesLookupType, ctx); + + +#if COREFX + Type finalType = type.CreateTypeInfo().AsType(); +#else + Type finalType = type.CreateType(); +#endif + if (!string.IsNullOrEmpty(path)) + { +#if COREFX + throw new NotSupportedException(CompilerOptions.NoPersistence); +#else + try + { + asm.Save(path); + } + catch (IOException ex) + { + // advertise the file info + throw new IOException(path + ", " + ex.Message, ex); + } + Helpers.DebugWriteLine("Wrote dll:" + path); +#endif + } + return (TypeModel)Activator.CreateInstance(finalType); + } + + private void WriteConstructors(TypeBuilder type, ref int index, SerializerPair[] methodPairs, ref ILGenerator il, int knownTypesCategory, FieldBuilder knownTypes, Type knownTypesLookupType, Compiler.CompilerContext ctx) + { + type.DefineDefaultConstructor(MethodAttributes.Public); + il = type.DefineTypeInitializer().GetILGenerator(); + switch (knownTypesCategory) + { + case KnownTypes_Array: + { + Compiler.CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newarr, ctx.MapType(typeof(System.Type))); + index = 0; + foreach (SerializerPair pair in methodPairs) + { + il.Emit(OpCodes.Dup); + Compiler.CompilerContext.LoadValue(il, index); + il.Emit(OpCodes.Ldtoken, pair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null); + il.Emit(OpCodes.Stelem_Ref); + index++; + } + il.Emit(OpCodes.Stsfld, knownTypes); + il.Emit(OpCodes.Ret); + } + break; + case KnownTypes_Dictionary: + { + Compiler.CompilerContext.LoadValue(il, types.Count); + //LocalBuilder loc = il.DeclareLocal(knownTypesLookupType); + il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) })); + il.Emit(OpCodes.Stsfld, knownTypes); + int typeIndex = 0; + foreach (SerializerPair pair in methodPairs) + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldtoken, pair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null); + int keyIndex = typeIndex++, lastKey = pair.BaseKey; + if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type + { + keyIndex = -1; // assume epic fail + for (int j = 0; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey) + { + keyIndex = j; + break; + } + } + } + Compiler.CompilerContext.LoadValue(il, keyIndex); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(System.Type)), MapType(typeof(int)) }), null); + } + il.Emit(OpCodes.Ret); + } + break; + case KnownTypes_Hashtable: + { + Compiler.CompilerContext.LoadValue(il, types.Count); + il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) })); + il.Emit(OpCodes.Stsfld, knownTypes); + int typeIndex = 0; + foreach (SerializerPair pair in methodPairs) + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldtoken, pair.Type.Type); + il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null); + int keyIndex = typeIndex++, lastKey = pair.BaseKey; + if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type + { + keyIndex = -1; // assume epic fail + for (int j = 0; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey) + { + keyIndex = j; + break; + } + } + } + Compiler.CompilerContext.LoadValue(il, keyIndex); + il.Emit(OpCodes.Box, MapType(typeof(int))); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(object)), MapType(typeof(object)) }), null); + } + il.Emit(OpCodes.Ret); + } + break; + default: + throw new InvalidOperationException(); + } + } + + private Compiler.CompilerContext WriteSerializeDeserialize(string assemblyName, TypeBuilder type, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, ref ILGenerator il) + { + il = Override(type, "Serialize"); + Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, true, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Serialize " + type.Name); + // arg0 = this, arg1 = key, arg2=obj, arg3=dest + Compiler.CodeLabel[] jumpTable = new Compiler.CodeLabel[types.Count]; + for (int i = 0; i < jumpTable.Length; i++) + { + jumpTable[i] = ctx.DefineLabel(); + } + il.Emit(OpCodes.Ldarg_1); + ctx.Switch(jumpTable); + ctx.Return(); + for (int i = 0; i < jumpTable.Length; i++) + { + SerializerPair pair = methodPairs[i]; + ctx.MarkLabel(jumpTable[i]); + il.Emit(OpCodes.Ldarg_2); + ctx.CastFromObject(pair.Type.Type); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, pair.Serialize, null); + ctx.Return(); + } + + il = Override(type, "Deserialize"); + ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)), "Deserialize " + type.Name); + // arg0 = this, arg1 = key, arg2=obj, arg3=source + for (int i = 0; i < jumpTable.Length; i++) + { + jumpTable[i] = ctx.DefineLabel(); + } + il.Emit(OpCodes.Ldarg_1); + ctx.Switch(jumpTable); + ctx.LoadNullRef(); + ctx.Return(); + for (int i = 0; i < jumpTable.Length; i++) + { + SerializerPair pair = methodPairs[i]; + ctx.MarkLabel(jumpTable[i]); + Type keyType = pair.Type.Type; + if (Helpers.IsValueType(keyType)) + { + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, EmitBoxedSerializer(type, i, keyType, methodPairs, this, ilVersion, assemblyName), null); + ctx.Return(); + } + else + { + il.Emit(OpCodes.Ldarg_2); + ctx.CastFromObject(keyType); + il.Emit(OpCodes.Ldarg_3); + il.EmitCall(OpCodes.Call, pair.Deserialize, null); + ctx.Return(); + } + } + return ctx; + } + + private const int KnownTypes_Array = 1, KnownTypes_Dictionary = 2, KnownTypes_Hashtable = 3, KnownTypes_ArrayCutoff = 20; + private void WriteGetKeyImpl(TypeBuilder type, bool hasInheritance, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName, out ILGenerator il, out int knownTypesCategory, out FieldBuilder knownTypes, out Type knownTypesLookupType) + { + + il = Override(type, "GetKeyImpl"); + Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(System.Type), true), "GetKeyImpl"); + + + if (types.Count <= KnownTypes_ArrayCutoff) + { + knownTypesCategory = KnownTypes_Array; + knownTypesLookupType = MapType(typeof(System.Type[]), true); + } + else + { + knownTypesLookupType = MapType(typeof(System.Collections.Generic.Dictionary), false); + +#if !COREFX + if (knownTypesLookupType == null) + { + knownTypesLookupType = MapType(typeof(Hashtable), true); + knownTypesCategory = KnownTypes_Hashtable; + } + else +#endif + { + knownTypesCategory = KnownTypes_Dictionary; + } + } + knownTypes = type.DefineField("knownTypes", knownTypesLookupType, FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static); + + switch (knownTypesCategory) + { + case KnownTypes_Array: + { + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + // note that Array.IndexOf is not supported under CF + il.EmitCall(OpCodes.Callvirt, MapType(typeof(IList)).GetMethod( + "IndexOf", new Type[] { MapType(typeof(object)) }), null); + if (hasInheritance) + { + il.DeclareLocal(MapType(typeof(int))); // loc-0 + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Stloc_0); + + BasicList getKeyLabels = new BasicList(); + int lastKey = -1; + for (int i = 0; i < methodPairs.Length; i++) + { + if (methodPairs[i].MetaKey == methodPairs[i].BaseKey) break; + if (lastKey == methodPairs[i].BaseKey) + { // add the last label again + getKeyLabels.Add(getKeyLabels[getKeyLabels.Count - 1]); + } + else + { // add a new unique label + getKeyLabels.Add(ctx.DefineLabel()); + lastKey = methodPairs[i].BaseKey; + } + } + Compiler.CodeLabel[] subtypeLabels = new Compiler.CodeLabel[getKeyLabels.Count]; + getKeyLabels.CopyTo(subtypeLabels, 0); + + ctx.Switch(subtypeLabels); + il.Emit(OpCodes.Ldloc_0); // not a sub-type; use the original value + il.Emit(OpCodes.Ret); + + lastKey = -1; + // now output the different branches per sub-type (not derived type) + for (int i = subtypeLabels.Length - 1; i >= 0; i--) + { + if (lastKey != methodPairs[i].BaseKey) + { + lastKey = methodPairs[i].BaseKey; + // find the actual base-index for this base-key (i.e. the index of + // the base-type) + int keyIndex = -1; + for (int j = subtypeLabels.Length; j < methodPairs.Length; j++) + { + if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey) + { + keyIndex = j; + break; + } + } + ctx.MarkLabel(subtypeLabels[i]); + Compiler.CompilerContext.LoadValue(il, keyIndex); + il.Emit(OpCodes.Ret); + } + } + } + else + { + il.Emit(OpCodes.Ret); + } + } + break; + case KnownTypes_Dictionary: + { + LocalBuilder result = il.DeclareLocal(MapType(typeof(int))); + Label otherwise = il.DefineLabel(); + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Ldloca_S, result); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("TryGetValue", BindingFlags.Instance | BindingFlags.Public), null); + il.Emit(OpCodes.Brfalse_S, otherwise); + il.Emit(OpCodes.Ldloc_S, result); + il.Emit(OpCodes.Ret); + il.MarkLabel(otherwise); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Ret); + } + break; + case KnownTypes_Hashtable: + { + Label otherwise = il.DefineLabel(); + il.Emit(OpCodes.Ldsfld, knownTypes); + il.Emit(OpCodes.Ldarg_1); + il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetProperty("Item").GetGetMethod(), null); + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Brfalse_S, otherwise); + if (ilVersion == Compiler.CompilerContext.ILVersion.Net1) + { + il.Emit(OpCodes.Unbox, MapType(typeof(int))); + il.Emit(OpCodes.Ldobj, MapType(typeof(int))); + } + else + { + il.Emit(OpCodes.Unbox_Any, MapType(typeof(int))); + } + il.Emit(OpCodes.Ret); + il.MarkLabel(otherwise); + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Ret); + } + break; + default: + throw new InvalidOperationException(); + } + } + + private void WriteSerializers(CompilerOptions options, string assemblyName, TypeBuilder type, out int index, out bool hasInheritance, out SerializerPair[] methodPairs, out Compiler.CompilerContext.ILVersion ilVersion) + { + Compiler.CompilerContext ctx; + + index = 0; + hasInheritance = false; + methodPairs = new SerializerPair[types.Count]; + foreach (MetaType metaType in types) + { + MethodBuilder writeMethod = type.DefineMethod("Write" +#if DEBUG + + metaType.Type.Name +#endif +, + MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, + MapType(typeof(void)), new Type[] { metaType.Type, MapType(typeof(ProtoWriter)) }); + + MethodBuilder readMethod = type.DefineMethod("Read" +#if DEBUG + + metaType.Type.Name +#endif +, + MethodAttributes.Private | MethodAttributes.Static, CallingConventions.Standard, + metaType.Type, new Type[] { metaType.Type, MapType(typeof(ProtoReader)) }); + + SerializerPair pair = new SerializerPair( + GetKey(metaType.Type, true, false), GetKey(metaType.Type, true, true), metaType, + writeMethod, readMethod, writeMethod.GetILGenerator(), readMethod.GetILGenerator()); + methodPairs[index++] = pair; + if (pair.MetaKey != pair.BaseKey) hasInheritance = true; + } + + if (hasInheritance) + { + Array.Sort(methodPairs); + } + + ilVersion = Compiler.CompilerContext.ILVersion.Net2; + if (options.MetaDataVersion == 0x10000) + { + ilVersion = Compiler.CompilerContext.ILVersion.Net1; // old-school! + } + for (index = 0; index < methodPairs.Length; index++) + { + SerializerPair pair = methodPairs[index]; + ctx = new Compiler.CompilerContext(pair.SerializeBody, true, true, methodPairs, this, ilVersion, assemblyName, pair.Type.Type, "SerializeImpl " + pair.Type.Type.Name); + MemberInfo returnType = pair.Deserialize.ReturnType +#if COREFX + .GetTypeInfo() +#endif + ; + ctx.CheckAccessibility(ref returnType); + pair.Type.Serializer.EmitWrite(ctx, ctx.InputValue); + ctx.Return(); + + ctx = new Compiler.CompilerContext(pair.DeserializeBody, true, false, methodPairs, this, ilVersion, assemblyName, pair.Type.Type, "DeserializeImpl " + pair.Type.Type.Name); + pair.Type.Serializer.EmitRead(ctx, ctx.InputValue); + if (!pair.Type.Serializer.ReturnsValue) + { + ctx.LoadValue(ctx.InputValue); + } + ctx.Return(); + } + } + + private TypeBuilder WriteBasicTypeModel(CompilerOptions options, string typeName, ModuleBuilder module) + { + Type baseType = MapType(typeof(TypeModel)); +#if COREFX + TypeAttributes typeAttributes = (baseType.GetTypeInfo().Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed; +#else + TypeAttributes typeAttributes = (baseType.Attributes & ~TypeAttributes.Abstract) | TypeAttributes.Sealed; +#endif + if (options.Accessibility == Accessibility.Internal) + { + typeAttributes &= ~TypeAttributes.Public; + } + + TypeBuilder type = module.DefineType(typeName, typeAttributes, baseType); + return type; + } + + private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm) + { + if (!string.IsNullOrEmpty(options.TargetFrameworkName)) + { + // get [TargetFramework] from mscorlib/equivalent and burn into the new assembly + Type versionAttribType = null; + try + { // this is best-endeavours only + versionAttribType = GetType("System.Runtime.Versioning.TargetFrameworkAttribute", Helpers.GetAssembly(MapType(typeof(string)))); + } + catch { /* don't stress */ } + if (versionAttribType != null) + { + PropertyInfo[] props; + object[] propValues; + if (string.IsNullOrEmpty(options.TargetFrameworkDisplayName)) + { + props = new PropertyInfo[0]; + propValues = new object[0]; + } + else + { + props = new PropertyInfo[1] { versionAttribType.GetProperty("FrameworkDisplayName") }; + propValues = new object[1] { options.TargetFrameworkDisplayName }; + } + CustomAttributeBuilder builder = new CustomAttributeBuilder( + versionAttribType.GetConstructor(new Type[] { MapType(typeof(string)) }), + new object[] { options.TargetFrameworkName }, + props, + propValues); + asm.SetCustomAttribute(builder); + } + } + + // copy assembly:InternalsVisibleTo + Type internalsVisibleToAttribType = null; + + try + { + internalsVisibleToAttribType = MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute)); + } + catch { /* best endeavors only */ } + + if (internalsVisibleToAttribType != null) + { + BasicList internalAssemblies = new BasicList(), consideredAssemblies = new BasicList(); + foreach (MetaType metaType in types) + { + Assembly assembly = Helpers.GetAssembly(metaType.Type); + if (consideredAssemblies.IndexOfReference(assembly) >= 0) continue; + consideredAssemblies.Add(assembly); + + AttributeMap[] assemblyAttribsMap = AttributeMap.Create(this, assembly); + for (int i = 0; i < assemblyAttribsMap.Length; i++) + { + + if (assemblyAttribsMap[i].AttributeType != internalsVisibleToAttribType) continue; + + object privelegedAssemblyObj; + assemblyAttribsMap[i].TryGet("AssemblyName", out privelegedAssemblyObj); + string privelegedAssemblyName = privelegedAssemblyObj as string; + if (privelegedAssemblyName == assemblyName || string.IsNullOrEmpty(privelegedAssemblyName)) continue; // ignore + + if (internalAssemblies.IndexOfString(privelegedAssemblyName) >= 0) continue; // seen it before + internalAssemblies.Add(privelegedAssemblyName); + + CustomAttributeBuilder builder = new CustomAttributeBuilder( + internalsVisibleToAttribType.GetConstructor(new Type[] { MapType(typeof(string)) }), + new object[] { privelegedAssemblyName }); + asm.SetCustomAttribute(builder); + } + } + } + } + + private static MethodBuilder EmitBoxedSerializer(TypeBuilder type, int i, Type valueType, SerializerPair[] methodPairs, TypeModel model, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName) + { + MethodInfo dedicated = methodPairs[i].Deserialize; + MethodBuilder boxedSerializer = type.DefineMethod("_" + i.ToString(), MethodAttributes.Static, CallingConventions.Standard, + model.MapType(typeof(object)), new Type[] { model.MapType(typeof(object)), model.MapType(typeof(ProtoReader)) }); + Compiler.CompilerContext ctx = new Compiler.CompilerContext(boxedSerializer.GetILGenerator(), true, false, methodPairs, model, ilVersion, assemblyName, model.MapType(typeof(object)), "BoxedSerializer " + valueType.Name); + ctx.LoadValue(ctx.InputValue); + Compiler.CodeLabel @null = ctx.DefineLabel(); + ctx.BranchIfFalse(@null, true); + + Type mappedValueType = valueType; + ctx.LoadValue(ctx.InputValue); + ctx.CastFromObject(mappedValueType); + ctx.LoadReaderWriter(); + ctx.EmitCall(dedicated); + ctx.CastToObject(mappedValueType); + ctx.Return(); + + ctx.MarkLabel(@null); + using (Compiler.Local typedVal = new Compiler.Local(ctx, mappedValueType)) + { + // create a new valueType + ctx.LoadAddress(typedVal, mappedValueType); + ctx.EmitCtor(mappedValueType); + ctx.LoadValue(typedVal); + ctx.LoadReaderWriter(); + ctx.EmitCall(dedicated); + ctx.CastToObject(mappedValueType); + ctx.Return(); + } + return boxedSerializer; + } + +#endif + //internal bool IsDefined(Type type, int fieldNumber) + //{ + // return FindWithoutAdd(type).IsDefined(fieldNumber); + //} + + // note that this is used by some of the unit tests + internal bool IsPrepared(Type type) + { + MetaType meta = FindWithoutAdd(type); + return meta != null && meta.IsPrepared(); + } + + internal EnumSerializer.EnumPair[] GetEnumMap(Type type) + { + int index = FindOrAddAuto(type, false, false, false); + return index < 0 ? null : ((MetaType)types[index]).GetEnumMap(); + } + + private int metadataTimeoutMilliseconds = 5000; + /// + /// The amount of time to wait if there are concurrent metadata access operations + /// + public int MetadataTimeoutMilliseconds + { + get { return metadataTimeoutMilliseconds; } + set + { + if (value <= 0) throw new ArgumentOutOfRangeException("MetadataTimeoutMilliseconds"); + metadataTimeoutMilliseconds = value; + } + } + +#if DEBUG + int lockCount; + /// + /// Gets how many times a model lock was taken + /// + public int LockCount { get { return lockCount; } } +#endif + internal void TakeLock(ref int opaqueToken) + { + const string message = "Timeout while inspecting metadata; this may indicate a deadlock. This can often be avoided by preparing necessary serializers during application initialization, rather than allowing multiple threads to perform the initial metadata inspection; please also see the LockContended event"; + opaqueToken = 0; +#if PORTABLE + if(!Monitor.TryEnter(types, metadataTimeoutMilliseconds)) throw new TimeoutException(message); + opaqueToken = Interlocked.CompareExchange(ref contentionCounter, 0, 0); // just fetch current value (starts at 1) +#elif CF2 || CF35 + int remaining = metadataTimeoutMilliseconds; + bool lockTaken; + do { + lockTaken = Monitor.TryEnter(types); + if(!lockTaken) + { + if(remaining <= 0) throw new TimeoutException(message); + remaining -= 50; + Thread.Sleep(50); + } + } while(!lockTaken); + opaqueToken = Interlocked.CompareExchange(ref contentionCounter, 0, 0); // just fetch current value (starts at 1) +#else + if (Monitor.TryEnter(types, metadataTimeoutMilliseconds)) + { + opaqueToken = GetContention(); // just fetch current value (starts at 1) + } + else + { + AddContention(); + + throw new TimeoutException(message); + } +#endif + +#if DEBUG // note that here, through all code-paths: we have the lock + lockCount++; +#endif + } + + private int contentionCounter = 1; +#if PLAT_NO_INTERLOCKED + private readonly object contentionLock = new object(); +#endif + private int GetContention() + { +#if PLAT_NO_INTERLOCKED + lock(contentionLock) + { + return contentionCounter; + } +#else + return Interlocked.CompareExchange(ref contentionCounter, 0, 0); +#endif + } + private void AddContention() + { +#if PLAT_NO_INTERLOCKED + lock(contentionLock) + { + contentionCounter++; + } +#else + Interlocked.Increment(ref contentionCounter); +#endif + } + + internal void ReleaseLock(int opaqueToken) + { + if (opaqueToken != 0) + { + Monitor.Exit(types); + if (opaqueToken != GetContention()) // contention-count changes since we looked! + { + LockContentedEventHandler handler = LockContended; + if (handler != null) + { + // not hugely elegant, but this is such a far-corner-case that it doesn't need to be slick - I'll settle for cross-platform + string stackTrace; + try + { + throw new ProtoException(); + } + catch (Exception ex) + { + stackTrace = ex.StackTrace; + } + + handler(this, new LockContentedEventArgs(stackTrace)); + } + } + } + } + /// + /// If a lock-contention is detected, this event signals the *owner* of the lock responsible for the blockage, indicating + /// what caused the problem; this is only raised if the lock-owning code successfully completes. + /// + public event LockContentedEventHandler LockContended; + + internal void ResolveListTypes(Type type, ref Type itemType, ref Type defaultType) + { + if (type == null) return; + if (Helpers.GetTypeCode(type) != ProtoTypeCode.Unknown) return; // don't try this[type] for inbuilts + + // handle arrays + if (type.IsArray) + { + if (type.GetArrayRank() != 1) + { + throw new NotSupportedException("Multi-dimension arrays are supported"); + } + itemType = type.GetElementType(); + if (itemType == MapType(typeof(byte))) + { + defaultType = itemType = null; + } + else + { + defaultType = type; + } + } + else + { + // if not an array, first check it isn't explicitly opted out + if (this[type].IgnoreListHandling) return; + } + + // handle lists + if (itemType == null) { itemType = TypeModel.GetListItemType(this, type); } + + // check for nested data (not allowed) + if (itemType != null) + { + Type nestedItemType = null, nestedDefaultType = null; + ResolveListTypes(itemType, ref nestedItemType, ref nestedDefaultType); + if (nestedItemType != null) + { + throw TypeModel.CreateNestedListsNotSupported(type); + } + } + + if (itemType != null && defaultType == null) + { +#if COREFX || PROFILE259 + TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(type); + if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null) +#else + if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null) +#endif + { + defaultType = type; + } + if (defaultType == null) + { +#if COREFX || PROFILE259 + if (typeInfo.IsInterface) +#else + if (type.IsInterface) +#endif + { + + Type[] genArgs; +#if COREFX || PROFILE259 + if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>) + && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments)) +#else + if (type.IsGenericType && type.GetGenericTypeDefinition() == MapType(typeof(System.Collections.Generic.IDictionary<,>)) + && itemType == MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments())) +#endif + { + defaultType = MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs); + } + else + { + defaultType = MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType); + } + } + } + // verify that the default type is appropriate + if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; } + } + } + + internal string GetSchemaTypeName(Type effectiveType, DataFormat dataFormat, bool asReference, bool dynamicType, ref CommonImports imports) + { + Type tmp = Helpers.GetUnderlyingType(effectiveType); + if (tmp != null) effectiveType = tmp; + + if (effectiveType == this.MapType(typeof(byte[]))) return "bytes"; + + WireType wireType; + IProtoSerializer ser = ValueMember.TryGetCoreSerializer(this, dataFormat, effectiveType, out wireType, false, false, false, false); + if (ser == null) + { // model type + if (asReference || dynamicType) + { + imports |= CommonImports.Bcl; + return ".bcl.NetObjectProxy"; + } + return this[effectiveType].GetSurrogateOrBaseOrSelf(true).GetSchemaTypeName(); + } + else + { + if (ser is ParseableSerializer) + { + if (asReference) imports |= CommonImports.Bcl; + return asReference ? ".bcl.NetObjectProxy" : "string"; + } + + switch (Helpers.GetTypeCode(effectiveType)) + { + case ProtoTypeCode.Boolean: return "bool"; + case ProtoTypeCode.Single: return "float"; + case ProtoTypeCode.Double: return "double"; + case ProtoTypeCode.String: + if (asReference) imports |= CommonImports.Bcl; + return asReference ? ".bcl.NetObjectProxy" : "string"; + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + switch (dataFormat) + { + case DataFormat.FixedSize: return "fixed32"; + default: return "uint32"; + } + case ProtoTypeCode.SByte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + switch (dataFormat) + { + case DataFormat.ZigZag: return "sint32"; + case DataFormat.FixedSize: return "sfixed32"; + default: return "int32"; + } + case ProtoTypeCode.UInt64: + switch (dataFormat) + { + case DataFormat.FixedSize: return "fixed64"; + default: return "uint64"; + } + case ProtoTypeCode.Int64: + switch (dataFormat) + { + case DataFormat.ZigZag: return "sint64"; + case DataFormat.FixedSize: return "sfixed64"; + default: return "int64"; + } + case ProtoTypeCode.DateTime: + switch (dataFormat) + { + case DataFormat.FixedSize: return "sint64"; + case DataFormat.WellKnown: + imports |= CommonImports.Timestamp; + return ".google.protobuf.Timestamp"; + default: + imports |= CommonImports.Bcl; + return ".bcl.DateTime"; + } + case ProtoTypeCode.TimeSpan: + switch (dataFormat) + { + case DataFormat.FixedSize: return "sint64"; + case DataFormat.WellKnown: + imports |= CommonImports.Duration; + return ".google.protobuf.Duration"; + default: + imports |= CommonImports.Bcl; + return ".bcl.TimeSpan"; + } + case ProtoTypeCode.Decimal: imports |= CommonImports.Bcl; return ".bcl.Decimal"; + case ProtoTypeCode.Guid: imports |= CommonImports.Bcl; return ".bcl.Guid"; + case ProtoTypeCode.Type: return "string"; + default: throw new NotSupportedException("No .proto map found for: " + effectiveType.FullName); + } + } + + } + + /// + /// Designate a factory-method to use to create instances of any type; note that this only affect types seen by the serializer *after* setting the factory. + /// + public void SetDefaultFactory(MethodInfo methodInfo) + { + VerifyFactory(methodInfo, null); + defaultFactory = methodInfo; + } + private MethodInfo defaultFactory; + + internal void VerifyFactory(MethodInfo factory, Type type) + { + if (factory != null) + { + if (type != null && Helpers.IsValueType(type)) throw new InvalidOperationException(); + if (!factory.IsStatic) throw new ArgumentException("A factory-method must be static", "factory"); + if ((type != null && factory.ReturnType != type) && factory.ReturnType != MapType(typeof(object))) throw new ArgumentException("The factory-method must return object" + (type == null ? "" : (" or " + type.FullName)), "factory"); + + if (!CallbackSet.CheckCallbackParameters(this, factory)) throw new ArgumentException("Invalid factory signature in " + factory.DeclaringType.FullName + "." + factory.Name, "factory"); + } + } + + /// + /// Raised before a type is auto-configured; this allows the auto-configuration to be electively suppressed + /// + /// This callback should be fast and not involve complex external calls, as it may block the model + public event EventHandler BeforeApplyDefaultBehaviour; + + /// + /// Raised after a type is auto-configured; this allows additional external customizations + /// + /// This callback should be fast and not involve complex external calls, as it may block the model + public event EventHandler AfterApplyDefaultBehaviour; + + internal static void OnBeforeApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) + => OnApplyDefaultBehaviour((metaType?.Model as RuntimeTypeModel)?.BeforeApplyDefaultBehaviour, metaType, ref args); + + internal static void OnAfterApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) + => OnApplyDefaultBehaviour((metaType?.Model as RuntimeTypeModel)?.AfterApplyDefaultBehaviour, metaType, ref args); + + private static void OnApplyDefaultBehaviour( + EventHandler handler, MetaType metaType, ref TypeAddedEventArgs args) + { + if (handler != null) + { + if (args == null) args = new TypeAddedEventArgs(metaType); + handler(metaType.Model, args); + } + } + } + + /// + /// Contains the stack-trace of the owning code when a lock-contention scenario is detected + /// + public sealed class LockContentedEventArgs : EventArgs + { + private readonly string ownerStackTrace; + internal LockContentedEventArgs(string ownerStackTrace) + { + this.ownerStackTrace = ownerStackTrace; + } + + /// + /// The stack-trace of the code that owned the lock when a lock-contention scenario occurred + /// + public string OwnerStackTrace => ownerStackTrace; + } + /// + /// Event-type that is raised when a lock-contention scenario is detected + /// + public delegate void LockContentedEventHandler(object sender, LockContentedEventArgs args); +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta new file mode 100644 index 00000000..231a0285 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/RuntimeTypeModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e4440bfa9e92f84d81d48e6c5b0022e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/SubType.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/SubType.cs new file mode 100644 index 00000000..72c81265 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/SubType.cs @@ -0,0 +1,97 @@ +#if !NO_RUNTIME +using System; +using System.Collections.Generic; +using ProtoBuf.Serializers; + +namespace ProtoBuf.Meta +{ + /// + /// Represents an inherited type in a type hierarchy. + /// + public sealed class SubType + { + internal sealed class Comparer : System.Collections.IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as SubType, y as SubType); + } + + public int Compare(SubType x, SubType y) + { + if (ReferenceEquals(x, y)) return 0; + if (x == null) return -1; + if (y == null) return 1; + + return x.FieldNumber.CompareTo(y.FieldNumber); + } + } + + private int _fieldNumber; + + /// + /// The field-number that is used to encapsulate the data (as a nested + /// message) for the derived dype. + /// + public int FieldNumber + { + get => _fieldNumber; + internal set + { + if (_fieldNumber != value) + { + MetaType.AssertValidFieldNumber(value); + ThrowIfFrozen(); + _fieldNumber = value; + } + } + } + + private void ThrowIfFrozen() + { + if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); + } + + + /// + /// The sub-type to be considered. + /// + public MetaType DerivedType => derivedType; + private readonly MetaType derivedType; + + /// + /// Creates a new SubType instance. + /// + /// The field-number that is used to encapsulate the data (as a nested + /// message) for the derived dype. + /// The sub-type to be considered. + /// Specific encoding style to use; in particular, Grouped can be used to avoid buffering, but is not the default. + public SubType(int fieldNumber, MetaType derivedType, DataFormat format) + { + if (derivedType == null) throw new ArgumentNullException(nameof(derivedType)); + if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber)); + _fieldNumber = fieldNumber; + this.derivedType = derivedType; + this.dataFormat = format; + } + + private readonly DataFormat dataFormat; + + private IProtoSerializer serializer; + + internal IProtoSerializer Serializer => serializer ?? (serializer = BuildSerializer()); + + private IProtoSerializer BuildSerializer() + { + // note the caller here is MetaType.BuildSerializer, which already has the sync-lock + WireType wireType = WireType.String; + if(dataFormat == DataFormat.Group) wireType = WireType.StartGroup; // only one exception + + IProtoSerializer ser = new SubItemSerializer(derivedType.Type, derivedType.GetKey(false, false), derivedType, false); + return new TagDecorator(_fieldNumber, wireType, false, ser); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/SubType.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/SubType.cs.meta new file mode 100644 index 00000000..fb7fe45a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/SubType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2912d37917b74846bdcffe3daa174d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs new file mode 100644 index 00000000..399c638a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs @@ -0,0 +1,33 @@ +using System; + +namespace ProtoBuf.Meta +{ + /// + /// Event data associated with new types being added to a model + /// + public sealed class TypeAddedEventArgs : EventArgs + { + internal TypeAddedEventArgs(MetaType metaType) + { + MetaType = metaType; + ApplyDefaultBehaviour = true; + } + + /// + /// Whether or not to apply the default mapping behavior + /// + public bool ApplyDefaultBehaviour { get; set; } + /// + /// The configuration of the type being added + /// + public MetaType MetaType { get; } + /// + /// The type that was added to the model + /// + public Type Type => MetaType.Type; + /// + /// The model that is being changed + /// + public RuntimeTypeModel Model => MetaType.Model as RuntimeTypeModel; + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta new file mode 100644 index 00000000..8ac9b8f4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeAddedEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1500030a10d2168408f75fe907ce0568 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs new file mode 100644 index 00000000..3db09993 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs @@ -0,0 +1,64 @@ +using System; + +namespace ProtoBuf.Meta +{ + /// + /// Event arguments needed to perform type-formatting functions; this could be resolving a Type to a string suitable for serialization, or could + /// be requesting a Type from a string. If no changes are made, a default implementation will be used (from the assembly-qualified names). + /// + public class TypeFormatEventArgs : EventArgs + { + private Type type; + private string formattedName; + private readonly bool typeFixed; + /// + /// The type involved in this map; if this is initially null, a Type is expected to be provided for the string in FormattedName. + /// + public Type Type + { + get { return type; } + set + { + if (type != value) + { + if (typeFixed) throw new InvalidOperationException("The type is fixed and cannot be changed"); + type = value; + } + } + } + + /// + /// The formatted-name involved in this map; if this is initially null, a formatted-name is expected from the type in Type. + /// + public string FormattedName + { + get { return formattedName; } + set + { + if (formattedName != value) + { + if (!typeFixed) throw new InvalidOperationException("The formatted-name is fixed and cannot be changed"); + formattedName = value; + } + } + } + + internal TypeFormatEventArgs(string formattedName) + { + if (string.IsNullOrEmpty(formattedName)) throw new ArgumentNullException("formattedName"); + this.formattedName = formattedName; + // typeFixed = false; <== implicit + } + + internal TypeFormatEventArgs(Type type) + { + this.type = type ?? throw new ArgumentNullException(nameof(type)); + typeFixed = true; + } + } + + /// + /// Delegate type used to perform type-formatting functions; the sender originates as the type-model. + /// + public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args); +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta new file mode 100644 index 00000000..a21c2abf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeFormatEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d27afe6e96660d1418a49cf374e84ad0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs new file mode 100644 index 00000000..9b023a6e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; + +namespace ProtoBuf.Meta +{ + partial class TypeModel : + IProtoInput, + IProtoInput>, + IProtoInput, + IProtoOutput + { + static SerializationContext CreateContext(object userState) + { + if (userState == null) + return SerializationContext.Default; + if (userState is SerializationContext ctx) + return ctx; + + var obj = new SerializationContext { Context = userState }; + obj.Freeze(); + return obj; + } + T IProtoInput.Deserialize(Stream source, T value, object userState) + => (T)Deserialize(source, value, typeof(T), CreateContext(userState)); + + T IProtoInput>.Deserialize(ArraySegment source, T value, object userState) + { + using (var ms = new MemoryStream(source.Array, source.Offset, source.Count)) + { + return (T)Deserialize(ms, value, typeof(T), CreateContext(userState)); + } + } + + T IProtoInput.Deserialize(byte[] source, T value, object userState) + { + using (var ms = new MemoryStream(source)) + { + return (T)Deserialize(ms, value, typeof(T), CreateContext(userState)); + } + } + + void IProtoOutput.Serialize(Stream destination, T value, object userState) + => Serialize(destination, value, CreateContext(userState)); + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta new file mode 100644 index 00000000..80015e59 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.InputOutput.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d683bc55be70e8e46824012108beb15f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.cs new file mode 100644 index 00000000..1867cf2e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.cs @@ -0,0 +1,1696 @@ +using System; +using System.IO; + +using System.Collections; +using System.Collections.Generic; +using System.Reflection; + +namespace ProtoBuf.Meta +{ + /// + /// Provides protobuf serialization support for a number of types + /// + public abstract partial class TypeModel + { +#if COREFX + internal TypeInfo MapType(TypeInfo type) + { + return type; + } +#endif + + /// + /// Should the Kind be included on date/time values? + /// + protected internal virtual bool SerializeDateTimeKind() { return false; } + + /// + /// Resolve a System.Type to the compiler-specific type + /// + protected internal Type MapType(Type type) + { + return MapType(type, true); + } + /// + /// Resolve a System.Type to the compiler-specific type + /// + protected internal virtual Type MapType(Type type, bool demand) + { + return type; + } + + private WireType GetWireType(ProtoTypeCode code, DataFormat format, ref Type type, out int modelKey) + { + modelKey = -1; + if (Helpers.IsEnum(type)) + { + modelKey = GetKey(ref type); + return WireType.Variant; + } + switch (code) + { + case ProtoTypeCode.Int64: + case ProtoTypeCode.UInt64: + return format == DataFormat.FixedSize ? WireType.Fixed64 : WireType.Variant; + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.Boolean: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + return format == DataFormat.FixedSize ? WireType.Fixed32 : WireType.Variant; + case ProtoTypeCode.Double: + return WireType.Fixed64; + case ProtoTypeCode.Single: + return WireType.Fixed32; + case ProtoTypeCode.String: + case ProtoTypeCode.DateTime: + case ProtoTypeCode.Decimal: + case ProtoTypeCode.ByteArray: + case ProtoTypeCode.TimeSpan: + case ProtoTypeCode.Guid: + case ProtoTypeCode.Uri: + return WireType.String; + } + + if ((modelKey = GetKey(ref type)) >= 0) + { + return WireType.String; + } + return WireType.None; + } + + + /// + /// This is the more "complete" version of Serialize, which handles single instances of mapped types. + /// The value is written as a complete field, including field-header and (for sub-objects) a + /// length-prefix + /// In addition to that, this provides support for: + /// - basic values; individual int / string / Guid / etc + /// - IEnumerable sequences of any type handled by TrySerializeAuxiliaryType + /// + /// + internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value, bool isInsideList, object parentList) + { + if (type == null) { type = value.GetType(); } + + ProtoTypeCode typecode = Helpers.GetTypeCode(type); + // note the "ref type" here normalizes against proxies + WireType wireType = GetWireType(typecode, format, ref type, out int modelKey); + + + if (modelKey >= 0) + { // write the header, but defer to the model + if (Helpers.IsEnum(type)) + { // no header + Serialize(modelKey, value, writer); + return true; + } + else + { + ProtoWriter.WriteFieldHeader(tag, wireType, writer); + switch (wireType) + { + case WireType.None: + throw ProtoWriter.CreateException(writer); + case WireType.StartGroup: + case WireType.String: + // needs a wrapping length etc + SubItemToken token = ProtoWriter.StartSubItem(value, writer); + Serialize(modelKey, value, writer); + ProtoWriter.EndSubItem(token, writer); + return true; + default: + Serialize(modelKey, value, writer); + return true; + } + } + } + + if (wireType != WireType.None) + { + ProtoWriter.WriteFieldHeader(tag, wireType, writer); + } + switch (typecode) + { + case ProtoTypeCode.Int16: ProtoWriter.WriteInt16((short)value, writer); return true; + case ProtoTypeCode.Int32: ProtoWriter.WriteInt32((int)value, writer); return true; + case ProtoTypeCode.Int64: ProtoWriter.WriteInt64((long)value, writer); return true; + case ProtoTypeCode.UInt16: ProtoWriter.WriteUInt16((ushort)value, writer); return true; + case ProtoTypeCode.UInt32: ProtoWriter.WriteUInt32((uint)value, writer); return true; + case ProtoTypeCode.UInt64: ProtoWriter.WriteUInt64((ulong)value, writer); return true; + case ProtoTypeCode.Boolean: ProtoWriter.WriteBoolean((bool)value, writer); return true; + case ProtoTypeCode.SByte: ProtoWriter.WriteSByte((sbyte)value, writer); return true; + case ProtoTypeCode.Byte: ProtoWriter.WriteByte((byte)value, writer); return true; + case ProtoTypeCode.Char: ProtoWriter.WriteUInt16((ushort)(char)value, writer); return true; + case ProtoTypeCode.Double: ProtoWriter.WriteDouble((double)value, writer); return true; + case ProtoTypeCode.Single: ProtoWriter.WriteSingle((float)value, writer); return true; + case ProtoTypeCode.DateTime: + if (SerializeDateTimeKind()) + BclHelpers.WriteDateTimeWithKind((DateTime)value, writer); + else + BclHelpers.WriteDateTime((DateTime)value, writer); + return true; + case ProtoTypeCode.Decimal: BclHelpers.WriteDecimal((decimal)value, writer); return true; + case ProtoTypeCode.String: ProtoWriter.WriteString((string)value, writer); return true; + case ProtoTypeCode.ByteArray: ProtoWriter.WriteBytes((byte[])value, writer); return true; + case ProtoTypeCode.TimeSpan: BclHelpers.WriteTimeSpan((TimeSpan)value, writer); return true; + case ProtoTypeCode.Guid: BclHelpers.WriteGuid((Guid)value, writer); return true; + case ProtoTypeCode.Uri: ProtoWriter.WriteString(((Uri)value).OriginalString, writer); return true; + } + + // by now, we should have covered all the simple cases; if we wrote a field-header, we have + // forgotten something! + Helpers.DebugAssert(wireType == WireType.None); + + // now attempt to handle sequences (including arrays and lists) + if (value is IEnumerable sequence) + { + if (isInsideList) throw CreateNestedListsNotSupported(parentList?.GetType()); + foreach (object item in sequence) + { + if (item == null) { throw new NullReferenceException(); } + if (!TrySerializeAuxiliaryType(writer, null, format, tag, item, true, sequence)) + { + ThrowUnexpectedType(item.GetType()); + } + } + return true; + } + return false; + } + + private void SerializeCore(ProtoWriter writer, object value) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + Type type = value.GetType(); + int key = GetKey(ref type); + if (key >= 0) + { + Serialize(key, value, writer); + } + else if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false, null)) + { + ThrowUnexpectedType(type); + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + public void Serialize(Stream dest, object value) + { + Serialize(dest, value, null); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + /// Additional information about this serialization operation. + public void Serialize(Stream dest, object value, SerializationContext context) + { + using (ProtoWriter writer = ProtoWriter.Create(dest, this, context)) + { + writer.SetRootObject(value); + SerializeCore(writer, value); + writer.Close(); + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied writer. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination writer to write to. + public void Serialize(ProtoWriter dest, object value) + { + if (dest == null) throw new ArgumentNullException(nameof(dest)); + dest.CheckDepthFlushlock(); + dest.SetRootObject(value); + SerializeCore(dest, value); + dest.CheckDepthFlushlock(); + ProtoWriter.Flush(dest); + } + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int fieldNumber) + => DeserializeWithLengthPrefix(source, value, type, style, fieldNumber, null, out long bytesRead); + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Used to resolve types on a per-field basis. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver) + => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead); + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Used to resolve types on a per-field basis. + /// Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out int bytesRead) + { + object result = DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead64, out bool haveObject, null); + bytesRead = checked((int)bytesRead64); + return result; + } + + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Used to resolve types on a per-field basis. + /// Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead) => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out bool haveObject, null); + + private object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, out long bytesRead, out bool haveObject, SerializationContext context) + { + haveObject = false; + bool skip; + long len; + bytesRead = 0; + if (type == null && (style != PrefixStyle.Base128 || resolver == null)) + { + throw new InvalidOperationException("A type must be provided unless base-128 prefixing is being used in combination with a resolver"); + } + do + { + + bool expectPrefix = expectedField > 0 || resolver != null; + len = ProtoReader.ReadLongLengthPrefix(source, expectPrefix, style, out int actualField, out int tmpBytesRead); + if (tmpBytesRead == 0) return value; + bytesRead += tmpBytesRead; + if (len < 0) return value; + + switch (style) + { + case PrefixStyle.Base128: + if (expectPrefix && expectedField == 0 && type == null && resolver != null) + { + type = resolver(actualField); + skip = type == null; + } + else { skip = expectedField != actualField; } + break; + default: + skip = false; + break; + } + + if (skip) + { + if (len == long.MaxValue) throw new InvalidOperationException(); + ProtoReader.Seek(source, len, null); + bytesRead += len; + } + } while (skip); + + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(source, this, context, len); + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + value = Deserialize(key, value, reader); + } + else + { + if (!(TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null) || len == 0)) + { + TypeModel.ThrowUnexpectedType(type); // throws + } + } + bytesRead += reader.LongPosition; + haveObject = true; + return value; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). + /// The type of object to deserialize (can be null if "resolver" is specified). + /// The sequence of deserialized objects. + public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver) + { + return DeserializeItems(source, type, style, expectedField, resolver, null); + } + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). + /// The type of object to deserialize (can be null if "resolver" is specified). + /// The sequence of deserialized objects. + /// Additional information about this serialization operation. + public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context) + { + return new DeserializeItemsIterator(this, source, type, style, expectedField, resolver, context); + } + + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The type of object to deserialize. + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// The sequence of deserialized objects. + public IEnumerable DeserializeItems(Stream source, PrefixStyle style, int expectedField) + { + return DeserializeItems(source, style, expectedField, null); + } + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignores for fixed-length prefixes. + /// + /// The type of object to deserialize. + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// The sequence of deserialized objects. + /// Additional information about this serialization operation. + public IEnumerable DeserializeItems(Stream source, PrefixStyle style, int expectedField, SerializationContext context) + { + return new DeserializeItemsIterator(this, source, style, expectedField, context); + } + + private sealed class DeserializeItemsIterator : DeserializeItemsIterator, + IEnumerator, + IEnumerable + { + IEnumerator IEnumerable.GetEnumerator() { return this; } + public new T Current { get { return (T)base.Current; } } + void IDisposable.Dispose() { } + public DeserializeItemsIterator(TypeModel model, Stream source, PrefixStyle style, int expectedField, SerializationContext context) + : base(model, source, model.MapType(typeof(T)), style, expectedField, null, context) { } + } + + private class DeserializeItemsIterator : IEnumerator, IEnumerable + { + IEnumerator IEnumerable.GetEnumerator() { return this; } + private bool haveObject; + private object current; + public bool MoveNext() + { + if (haveObject) + { + current = model.DeserializeWithLengthPrefix(source, null, type, style, expectedField, resolver, out long bytesRead, out haveObject, context); + } + return haveObject; + } + void IEnumerator.Reset() { throw new NotSupportedException(); } + public object Current { get { return current; } } + private readonly Stream source; + private readonly Type type; + private readonly PrefixStyle style; + private readonly int expectedField; + private readonly Serializer.TypeResolver resolver; + private readonly TypeModel model; + private readonly SerializationContext context; + public DeserializeItemsIterator(TypeModel model, Stream source, Type type, PrefixStyle style, int expectedField, Serializer.TypeResolver resolver, SerializationContext context) + { + haveObject = true; + this.source = source; + this.type = type; + this.style = style; + this.expectedField = expectedField; + this.resolver = resolver; + this.model = model; + this.context = context; + } + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber) + { + SerializeWithLengthPrefix(dest, value, type, style, fieldNumber, null); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + /// Additional information about this serialization operation. + public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context) + { + if (type == null) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + type = MapType(value.GetType()); + } + int key = GetKey(ref type); + using (ProtoWriter writer = ProtoWriter.Create(dest, this, context)) + { + switch (style) + { + case PrefixStyle.None: + Serialize(key, value, writer); + break; + case PrefixStyle.Base128: + case PrefixStyle.Fixed32: + case PrefixStyle.Fixed32BigEndian: + ProtoWriter.WriteObject(value, key, writer, style, fieldNumber); + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + writer.Close(); + } + } + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(Stream source, object value, Type type) + { + return Deserialize(source, value, type, null); + } + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + /// Additional information about this serialization operation. + public object Deserialize(Stream source, object value, Type type, SerializationContext context) + { + bool autoCreate = PrepareDeserialize(value, ref type); + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(source, this, context, ProtoReader.TO_EOF); + if (value != null) reader.SetRootObject(value); + object obj = DeserializeCore(reader, type, value, autoCreate); + reader.CheckFullyConsumed(); + return obj; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + private bool PrepareDeserialize(object value, ref Type type) + { + if (type == null) + { + if (value == null) + { + throw new ArgumentNullException(nameof(type)); + } + else + { + type = MapType(value.GetType()); + } + } + + bool autoCreate = true; + Type underlyingType = Helpers.GetUnderlyingType(type); + if (underlyingType != null) + { + type = underlyingType; + autoCreate = false; + } + return autoCreate; + } + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(Stream source, object value, System.Type type, int length) + => Deserialize(source, value, type, length, null); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(Stream source, object value, System.Type type, long length) + => Deserialize(source, value, type, length, null); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume (or -1 to read to the end of the stream). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + /// Additional information about this serialization operation. + public object Deserialize(Stream source, object value, System.Type type, int length, SerializationContext context) + => Deserialize(source, value, type, length == int.MaxValue ? long.MaxValue : (long)length, context); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The number of bytes to consume (or -1 to read to the end of the stream). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + /// Additional information about this serialization operation. + public object Deserialize(Stream source, object value, System.Type type, long length, SerializationContext context) + { + bool autoCreate = PrepareDeserialize(value, ref type); + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(source, this, context, length); + if (value != null) reader.SetRootObject(value); + object obj = DeserializeCore(reader, type, value, autoCreate); + reader.CheckFullyConsumed(); + return obj; + } + finally + { + ProtoReader.Recycle(reader); + } + } + + /// + /// Applies a protocol-buffer reader to an existing instance (which may be null). + /// + /// The type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The reader to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public object Deserialize(ProtoReader source, object value, System.Type type) + { + if (source == null) throw new ArgumentNullException("source"); + bool autoCreate = PrepareDeserialize(value, ref type); + if (value != null) source.SetRootObject(value); + object obj = DeserializeCore(source, type, value, autoCreate); + source.CheckFullyConsumed(); + return obj; + } + + private object DeserializeCore(ProtoReader reader, Type type, object value, bool noAutoCreate) + { + int key = GetKey(ref type); + if (key >= 0 && !Helpers.IsEnum(type)) + { + return Deserialize(key, value, reader); + } + // this returns true to say we actively found something, but a value is assigned either way (or throws) + TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, noAutoCreate, false, null); + return value; + } + +#if COREFX + private static readonly System.Reflection.TypeInfo ilist = typeof(IList).GetTypeInfo(); +#else + private static readonly System.Type ilist = typeof(IList); +#endif + internal static MethodInfo ResolveListAdd(TypeModel model, Type listType, Type itemType, out bool isList) + { +#if COREFX || PROFILE259 + TypeInfo listTypeInfo = listType.GetTypeInfo(); +#else + Type listTypeInfo = listType; +#endif +#if PROFILE259 + isList = model.MapType(ilist).GetTypeInfo().IsAssignableFrom(listTypeInfo); +#else + isList = model.MapType(ilist).IsAssignableFrom(listTypeInfo); +#endif + Type[] types = { itemType }; + MethodInfo add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types); + +#if !NO_GENERICS + if (add == null) + { // fallback: look for ICollection's Add(typedObject) method + + bool forceList = listTypeInfo.IsInterface && + model.MapType(typeof(System.Collections.Generic.IEnumerable<>)).MakeGenericType(types) +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsAssignableFrom(listTypeInfo); + +#if COREFX || PROFILE259 + TypeInfo constuctedListType = typeof(System.Collections.Generic.ICollection<>).MakeGenericType(types).GetTypeInfo(); +#else + Type constuctedListType = model.MapType(typeof(System.Collections.Generic.ICollection<>)).MakeGenericType(types); +#endif + if (forceList || constuctedListType.IsAssignableFrom(listTypeInfo)) + { + add = Helpers.GetInstanceMethod(constuctedListType, "Add", types); + } + } + + if (add == null) + { + +#if COREFX || PROFILE259 + foreach (Type tmpType in listTypeInfo.ImplementedInterfaces) +#else + foreach (Type interfaceType in listTypeInfo.GetInterfaces()) +#endif + { +#if COREFX || PROFILE259 + TypeInfo interfaceType = tmpType.GetTypeInfo(); +#endif + if (interfaceType.Name == "IProducerConsumerCollection`1" && interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + add = Helpers.GetInstanceMethod(interfaceType, "TryAdd", types); + if (add != null) break; + } + } + } +#endif + + if (add == null) + { // fallback: look for a public list.Add(object) method + types[0] = model.MapType(typeof(object)); + add = Helpers.GetInstanceMethod(listTypeInfo, "Add", types); + } + if (add == null && isList) + { // fallback: look for IList's Add(object) method + add = Helpers.GetInstanceMethod(model.MapType(ilist), "Add", types); + } + return add; + } + internal static Type GetListItemType(TypeModel model, Type listType) + { + Helpers.DebugAssert(listType != null); + +#if PROFILE259 + TypeInfo listTypeInfo = listType.GetTypeInfo(); + if (listType == typeof(string) || listType.IsArray + || !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(listTypeInfo)) return null; +#else + if (listType == model.MapType(typeof(string)) || listType.IsArray + || !model.MapType(typeof(IEnumerable)).IsAssignableFrom(listType)) return null; +#endif + + BasicList candidates = new BasicList(); +#if PROFILE259 + foreach (MethodInfo method in listType.GetRuntimeMethods()) +#else + foreach (MethodInfo method in listType.GetMethods()) +#endif + { + if (method.IsStatic || method.Name != "Add") continue; + ParameterInfo[] parameters = method.GetParameters(); + Type paramType; + if (parameters.Length == 1 && !candidates.Contains(paramType = parameters[0].ParameterType)) + { + candidates.Add(paramType); + } + } + + string name = listType.Name; + bool isQueueStack = name != null && (name.IndexOf("Queue") >= 0 || name.IndexOf("Stack") >= 0); + + if (!isQueueStack) + { + TestEnumerableListPatterns(model, candidates, listType); +#if PROFILE259 + foreach (Type iType in listTypeInfo.ImplementedInterfaces) + { + TestEnumerableListPatterns(model, candidates, iType); + } +#else + foreach (Type iType in listType.GetInterfaces()) + { + TestEnumerableListPatterns(model, candidates, iType); + } +#endif + } + +#if PROFILE259 + // more convenient GetProperty overload not supported on all platforms + foreach (PropertyInfo indexer in listType.GetRuntimeProperties()) + { + if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue; + ParameterInfo[] args = indexer.GetIndexParameters(); + if (args.Length != 1 || args[0].ParameterType != typeof(int)) continue; + MethodInfo getter = indexer.GetMethod; + if (getter == null || getter.IsStatic) continue; + candidates.Add(indexer.PropertyType); + } +#else + // more convenient GetProperty overload not supported on all platforms + foreach (PropertyInfo indexer in listType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (indexer.Name != "Item" || candidates.Contains(indexer.PropertyType)) continue; + ParameterInfo[] args = indexer.GetIndexParameters(); + if (args.Length != 1 || args[0].ParameterType != model.MapType(typeof(int))) continue; + candidates.Add(indexer.PropertyType); + } +#endif + + switch (candidates.Count) + { + case 0: + return null; + case 1: + if ((Type)candidates[0] == listType) return null; // recursive + return (Type)candidates[0]; + case 2: + if ((Type)candidates[0] != listType && CheckDictionaryAccessors(model, (Type)candidates[0], (Type)candidates[1])) return (Type)candidates[0]; + if ((Type)candidates[1] != listType && CheckDictionaryAccessors(model, (Type)candidates[1], (Type)candidates[0])) return (Type)candidates[1]; + break; + } + + return null; + } + + private static void TestEnumerableListPatterns(TypeModel model, BasicList candidates, Type iType) + { + +#if COREFX || PROFILE259 + TypeInfo iTypeInfo = iType.GetTypeInfo(); + if (iTypeInfo.IsGenericType) + { + Type typeDef = iTypeInfo.GetGenericTypeDefinition(); + if( + typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>)) + || typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>)) + || typeDef.GetTypeInfo().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + + Type[] iTypeArgs = iTypeInfo.GenericTypeArguments; + if (!candidates.Contains(iTypeArgs[0])) + { + candidates.Add(iTypeArgs[0]); + } + } + } +#else + if (iType.IsGenericType) + { + Type typeDef = iType.GetGenericTypeDefinition(); + if (typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable<>)) + || typeDef == model.MapType(typeof(System.Collections.Generic.ICollection<>)) + || typeDef.FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1") + { + Type[] iTypeArgs = iType.GetGenericArguments(); + if (!candidates.Contains(iTypeArgs[0])) + { + candidates.Add(iTypeArgs[0]); + } + } + } +#endif + } + + private static bool CheckDictionaryAccessors(TypeModel model, Type pair, Type value) + { +#if COREFX || PROFILE259 + TypeInfo finalType = pair.GetTypeInfo(); + return finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>) + && finalType.GenericTypeArguments[1] == value; +#else + return pair.IsGenericType && pair.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)) + && pair.GetGenericArguments()[1] == value; +#endif + } + + private bool TryDeserializeList(TypeModel model, ProtoReader reader, DataFormat format, int tag, Type listType, Type itemType, ref object value) + { + MethodInfo addMethod = TypeModel.ResolveListAdd(model, listType, itemType, out bool isList); + if (addMethod == null) throw new NotSupportedException("Unknown list variant: " + listType.FullName); + bool found = false; + object nextItem = null; + IList list = value as IList; + object[] args = isList ? null : new object[1]; + BasicList arraySurrogate = listType.IsArray ? new BasicList() : null; + + while (TryDeserializeAuxiliaryType(reader, format, tag, itemType, ref nextItem, true, true, true, true, value ?? listType)) + { + found = true; + if (value == null && arraySurrogate == null) + { + value = CreateListInstance(listType, itemType); + list = value as IList; + } + if (list != null) + { + list.Add(nextItem); + } + else if (arraySurrogate != null) + { + arraySurrogate.Add(nextItem); + } + else + { + args[0] = nextItem; + addMethod.Invoke(value, args); + } + nextItem = null; + } + if (arraySurrogate != null) + { + Array newArray; + if (value != null) + { + if (arraySurrogate.Count == 0) + { // we'll stay with what we had, thanks + } + else + { + Array existing = (Array)value; + newArray = Array.CreateInstance(itemType, existing.Length + arraySurrogate.Count); + Array.Copy(existing, newArray, existing.Length); + arraySurrogate.CopyTo(newArray, existing.Length); + value = newArray; + } + } + else + { + newArray = Array.CreateInstance(itemType, arraySurrogate.Count); + arraySurrogate.CopyTo(newArray, 0); + value = newArray; + } + } + return found; + } + + private static object CreateListInstance(Type listType, Type itemType) + { + Type concreteListType = listType; + + if (listType.IsArray) + { + return Array.CreateInstance(itemType, 0); + } + +#if COREFX || PROFILE259 + TypeInfo listTypeInfo = listType.GetTypeInfo(); + if (!listTypeInfo.IsClass || listTypeInfo.IsAbstract || + Helpers.GetConstructor(listTypeInfo, Helpers.EmptyTypes, true) == null) +#else + if (!listType.IsClass || listType.IsAbstract || + Helpers.GetConstructor(listType, Helpers.EmptyTypes, true) == null) +#endif + { + string fullName; + bool handled = false; +#if COREFX || PROFILE259 + if (listTypeInfo.IsInterface && +#else + if (listType.IsInterface && +#endif + (fullName = listType.FullName) != null && fullName.IndexOf("Dictionary") >= 0) // have to try to be frugal here... + { +#if COREFX || PROFILE259 + TypeInfo finalType = listType.GetTypeInfo(); + if (finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)) + { + Type[] genericTypes = listType.GenericTypeArguments; + concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes); + handled = true; + } +#else + if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)) + { + Type[] genericTypes = listType.GetGenericArguments(); + concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes); + handled = true; + } +#endif + +#if !PORTABLE && !COREFX && !PROFILE259 + if (!handled && listType == typeof(IDictionary)) + { + concreteListType = typeof(Hashtable); + handled = true; + } +#endif + } + + if (!handled) + { + concreteListType = typeof(System.Collections.Generic.List<>).MakeGenericType(itemType); + handled = true; + } + +#if !PORTABLE && !COREFX && !PROFILE259 + if (!handled) + { + concreteListType = typeof(ArrayList); + handled = true; + } +#endif + } + return Activator.CreateInstance(concreteListType); + } + + /// + /// This is the more "complete" version of Deserialize, which handles single instances of mapped types. + /// The value is read as a complete field, including field-header and (for sub-objects) a + /// length-prefix..kmc + /// + /// In addition to that, this provides support for: + /// - basic values; individual int / string / Guid / etc + /// - IList sets of any type handled by TryDeserializeAuxiliaryType + /// + internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList, object parentListOrType) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + Type itemType = null; + ProtoTypeCode typecode = Helpers.GetTypeCode(type); + WireType wiretype = GetWireType(typecode, format, ref type, out int modelKey); + + bool found = false; + if (wiretype == WireType.None) + { + itemType = GetListItemType(this, type); + if (itemType == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[])) + { + itemType = type.GetElementType(); + } + if (itemType != null) + { + if (insideList) throw TypeModel.CreateNestedListsNotSupported((parentListOrType as Type) ?? (parentListOrType?.GetType())); + found = TryDeserializeList(this, reader, format, tag, type, itemType, ref value); + if (!found && autoCreate) + { + value = CreateListInstance(type, itemType); + } + return found; + } + + // otherwise, not a happy bunny... + ThrowUnexpectedType(type); + } + + // to treat correctly, should read all values + + while (true) + { + // for convenience (re complex exit conditions), additional exit test here: + // if we've got the value, are only looking for one, and we aren't a list - then exit + if (found && asListItem) break; + + + // read the next item + int fieldNumber = reader.ReadFieldHeader(); + if (fieldNumber <= 0) break; + if (fieldNumber != tag) + { + if (skipOtherFields) + { + reader.SkipField(); + continue; + } + throw ProtoReader.AddErrorData(new InvalidOperationException( + "Expected field " + tag.ToString() + ", but found " + fieldNumber.ToString()), reader); + } + found = true; + reader.Hint(wiretype); // handle signed data etc + + if (modelKey >= 0) + { + switch (wiretype) + { + case WireType.String: + case WireType.StartGroup: + SubItemToken token = ProtoReader.StartSubItem(reader); + value = Deserialize(modelKey, value, reader); + ProtoReader.EndSubItem(token, reader); + continue; + default: + value = Deserialize(modelKey, value, reader); + continue; + } + } + switch (typecode) + { + case ProtoTypeCode.Int16: value = reader.ReadInt16(); continue; + case ProtoTypeCode.Int32: value = reader.ReadInt32(); continue; + case ProtoTypeCode.Int64: value = reader.ReadInt64(); continue; + case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); continue; + case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); continue; + case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); continue; + case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); continue; + case ProtoTypeCode.SByte: value = reader.ReadSByte(); continue; + case ProtoTypeCode.Byte: value = reader.ReadByte(); continue; + case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); continue; + case ProtoTypeCode.Double: value = reader.ReadDouble(); continue; + case ProtoTypeCode.Single: value = reader.ReadSingle(); continue; + case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); continue; + case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); continue; + case ProtoTypeCode.String: value = reader.ReadString(); continue; + case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); continue; + case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); continue; + case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); continue; + case ProtoTypeCode.Uri: value = new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute); continue; + } + + } + if (!found && !asListItem && autoCreate) + { + if (type != typeof(string)) + { + value = Activator.CreateInstance(type); + } + } + return found; + } + +#if !NO_RUNTIME + /// + /// Creates a new runtime model, to which the caller + /// can add support for a range of types. A model + /// can be used "as is", or can be compiled for + /// optimal performance. + /// + [Obsolete("Please use RuntimeTypeModel.Create", false)] + public static RuntimeTypeModel Create() + { + return RuntimeTypeModel.Create(); + } +#endif + + /// + /// Applies common proxy scenarios, resolving the actual type to consider + /// + protected internal static Type ResolveProxies(Type type) + { + if (type == null) return null; +#if !NO_GENERICS + if (type.IsGenericParameter) return null; + // Nullable + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) return tmp; +#endif + +#if !CF + // EF POCO + string fullName = type.FullName; + if (fullName != null && fullName.StartsWith("System.Data.Entity.DynamicProxies.")) + { +#if COREFX || PROFILE259 + return type.GetTypeInfo().BaseType; +#else + return type.BaseType; +#endif + } + + // NHibernate +#if PROFILE259 + IEnumerable interfaces = type.GetTypeInfo().ImplementedInterfaces; +#else + Type[] interfaces = type.GetInterfaces(); +#endif + foreach (Type t in interfaces) + { + switch (t.FullName) + { + case "NHibernate.Proxy.INHibernateProxy": + case "NHibernate.Proxy.DynamicProxy.IProxy": + case "NHibernate.Intercept.IFieldInterceptorAccessor": +#if COREFX || PROFILE259 + return type.GetTypeInfo().BaseType; +#else + return type.BaseType; +#endif + } + } +#endif + return null; + } + + /// + /// Indicates whether the supplied type is explicitly modelled by the model + /// + public bool IsDefined(Type type) => GetKey(ref type) >= 0; + + readonly Dictionary knownKeys = new Dictionary(); + + // essentially just a ValueTuple - I just don't want the extra dependency + private readonly struct KnownTypeKey + { + public KnownTypeKey(Type type, int key) + { + Type = type; + Key = key; + } + + public int Key { get; } + + public Type Type { get; } + } + + /// + /// Provides the key that represents a given type in the current model. + /// The type is also normalized for proxies at the same time. + /// + protected internal int GetKey(ref Type type) + { + if (type == null) return -1; + int key; + lock (knownKeys) + { + if (knownKeys.TryGetValue(type, out var tuple)) + { + // the type can be changed via ResolveProxies etc +#if DEBUG + var actualKey = GetKeyImpl(type); + if(actualKey != tuple.Key) + { + throw new InvalidOperationException( + $"Key cache failure; got {tuple.Key} instead of {actualKey} for '{type.Name}'"); + } +#endif + type = tuple.Type; + return tuple.Key; + } + } + key = GetKeyImpl(type); + Type originalType = type; + if (key < 0) + { + Type normalized = ResolveProxies(type); + if (normalized != null && normalized != type) + { + type = normalized; // hence ref + key = GetKeyImpl(type); + } + } + lock (knownKeys) + { + knownKeys[originalType] = new KnownTypeKey(type, key); + } + return key; + } + + /// + /// Advertise that a type's key can have changed + /// + internal void ResetKeyCache() + { + // clear *everything* (think: multi-level - can be many descendents) + lock(knownKeys) + { + knownKeys.Clear(); + } + } + + /// + /// Provides the key that represents a given type in the current model. + /// + protected abstract int GetKeyImpl(Type type); + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + protected internal abstract void Serialize(int key, object value, ProtoWriter dest); + + /// + /// Applies a protocol-buffer stream to an existing instance (which may be null). + /// + /// Represents the type (including inheritance) to consider. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + protected internal abstract object Deserialize(int key, object value, ProtoReader source); + + //internal ProtoSerializer Create(IProtoSerializer head) + //{ + // return new RuntimeSerializer(head, this); + //} + //internal ProtoSerializer Compile + + /// + /// Indicates the type of callback to be used + /// + protected internal enum CallbackType + { + /// + /// Invoked before an object is serialized + /// + BeforeSerialize, + /// + /// Invoked after an object is serialized + /// + AfterSerialize, + /// + /// Invoked before an object is deserialized (or when a new instance is created) + /// + BeforeDeserialize, + /// + /// Invoked after an object is deserialized + /// + AfterDeserialize + } + + /// + /// Create a deep clone of the supplied instance; any sub-items are also cloned. + /// + public object DeepClone(object value) + { + if (value == null) return null; + Type type = value.GetType(); + int key = GetKey(ref type); + + if (key >= 0 && !Helpers.IsEnum(type)) + { + using (MemoryStream ms = new MemoryStream()) + { + using (ProtoWriter writer = ProtoWriter.Create(ms, this, null)) + { + writer.SetRootObject(value); + Serialize(key, value, writer); + writer.Close(); + } + ms.Position = 0; + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF); + return Deserialize(key, null, reader); + } + finally + { + ProtoReader.Recycle(reader); + } + } + } + if (type == typeof(byte[])) + { + byte[] orig = (byte[])value, clone = new byte[orig.Length]; + Buffer.BlockCopy(orig, 0, clone, 0, orig.Length); + return clone; + } + else if (GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out int modelKey) != WireType.None && modelKey < 0) + { // immutable; just return the original value + return value; + } + using (MemoryStream ms = new MemoryStream()) + { + using (ProtoWriter writer = ProtoWriter.Create(ms, this, null)) + { + if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value, false, null)) ThrowUnexpectedType(type); + writer.Close(); + } + ms.Position = 0; + ProtoReader reader = null; + try + { + reader = ProtoReader.Create(ms, this, null, ProtoReader.TO_EOF); + value = null; // start from scratch! + TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null); + return value; + } + finally + { + ProtoReader.Recycle(reader); + } + } + } + + /// + /// Indicates that while an inheritance tree exists, the exact type encountered was not + /// specified in that hierarchy and cannot be processed. + /// + protected internal static void ThrowUnexpectedSubtype(Type expected, Type actual) + { + if (expected != TypeModel.ResolveProxies(actual)) + { + throw new InvalidOperationException("Unexpected sub-type: " + actual.FullName); + } + } + + /// + /// Indicates that the given type was not expected, and cannot be processed. + /// + protected internal static void ThrowUnexpectedType(Type type) + { + string fullName = type == null ? "(unknown)" : type.FullName; + + if (type != null) + { + Type baseType = type +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .BaseType; + if (baseType != null && baseType +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsGenericType && baseType.GetGenericTypeDefinition().Name == "GeneratedMessage`2") + { + throw new InvalidOperationException( + "Are you mixing protobuf-net and protobuf-csharp-port? See https://stackoverflow.com/q/11564914/23354; type: " + fullName); + } + } + + throw new InvalidOperationException("Type is not expected, and no contract can be inferred: " + fullName); + } + + internal static Exception CreateNestedListsNotSupported(Type type) + { + return new NotSupportedException("Nested or jagged lists and arrays are not supported: " + (type?.FullName ?? "(null)")); + } + + /// + /// Indicates that the given type cannot be constructed; it may still be possible to + /// deserialize into existing instances. + /// + public static void ThrowCannotCreateInstance(Type type) + { + throw new ProtoException("No parameterless constructor found for " + (type?.FullName ?? "(null)")); + } + + internal static string SerializeType(TypeModel model, System.Type type) + { + if (model != null) + { + TypeFormatEventHandler handler = model.DynamicTypeFormatting; + if (handler != null) + { + TypeFormatEventArgs args = new TypeFormatEventArgs(type); + handler(model, args); + if (!string.IsNullOrEmpty(args.FormattedName)) return args.FormattedName; + } + } + return type.AssemblyQualifiedName; + } + + internal static Type DeserializeType(TypeModel model, string value) + { + + if (model != null) + { + TypeFormatEventHandler handler = model.DynamicTypeFormatting; + if (handler != null) + { + TypeFormatEventArgs args = new TypeFormatEventArgs(value); + handler(model, args); + if (args.Type != null) return args.Type; + } + } + return Type.GetType(value); + } + + /// + /// Returns true if the type supplied is either a recognised contract type, + /// or a *list* of a recognised contract type. + /// + /// Note that primitives always return false, even though the engine + /// will, if forced, try to serialize such + /// True if this type is recognised as a serializable entity, else false + public bool CanSerializeContractType(Type type) => CanSerialize(type, false, true, true); + + /// + /// Returns true if the type supplied is a basic type with inbuilt handling, + /// a recognised contract type, or a *list* of a basic / contract type. + /// + public bool CanSerialize(Type type) => CanSerialize(type, true, true, true); + + /// + /// Returns true if the type supplied is a basic type with inbuilt handling, + /// or a *list* of a basic type with inbuilt handling + /// + public bool CanSerializeBasicType(Type type) => CanSerialize(type, true, false, true); + + private bool CanSerialize(Type type, bool allowBasic, bool allowContract, bool allowLists) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + + // is it a basic type? + ProtoTypeCode typeCode = Helpers.GetTypeCode(type); + switch (typeCode) + { + case ProtoTypeCode.Empty: + case ProtoTypeCode.Unknown: + break; + default: + return allowBasic; // well-known basic type + } + int modelKey = GetKey(ref type); + if (modelKey >= 0) return allowContract; // known contract type + + // is it a list? + if (allowLists) + { + Type itemType = null; + if (type.IsArray) + { // note we don't need to exclude byte[], as that is handled by GetTypeCode already + if (type.GetArrayRank() == 1) itemType = type.GetElementType(); + } + else + { + itemType = GetListItemType(this, type); + } + if (itemType != null) return CanSerialize(itemType, allowBasic, allowContract, false); + } + return false; + } + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for, or null to generate a .proto that represents the entire model + /// The .proto definition as a string + public virtual string GetSchema(Type type) => GetSchema(type, ProtoSyntax.Proto2); + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for, or null to generate a .proto that represents the entire model + /// The .proto definition as a string + /// The .proto syntax to use for the operation + public virtual string GetSchema(Type type, ProtoSyntax syntax) + { + throw new NotSupportedException(); + } + + /// + /// Used to provide custom services for writing and parsing type names when using dynamic types. Both parsing and formatting + /// are provided on a single API as it is essential that both are mapped identically at all times. + /// + public event TypeFormatEventHandler DynamicTypeFormatting; + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Creates a new IFormatter that uses protocol-buffer [de]serialization. + /// + /// A new IFormatter to be used during [de]serialization. + /// The type of object to be [de]deserialized by the formatter. + public System.Runtime.Serialization.IFormatter CreateFormatter(Type type) + { + return new Formatter(this, type); + } + + internal sealed class Formatter : System.Runtime.Serialization.IFormatter + { + private readonly TypeModel model; + private readonly Type type; + internal Formatter(TypeModel model, Type type) + { + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.type = type ?? throw new ArgumentNullException(nameof(type)); + } + private System.Runtime.Serialization.SerializationBinder binder; + public System.Runtime.Serialization.SerializationBinder Binder + { + get { return binder; } + set { binder = value; } + } + + private System.Runtime.Serialization.StreamingContext context; + public System.Runtime.Serialization.StreamingContext Context + { + get { return context; } + set { context = value; } + } + + public object Deserialize(Stream source) + { + return model.Deserialize(source, null, type, (long)-1, Context); + } + + public void Serialize(Stream destination, object graph) + { + model.Serialize(destination, graph, Context); + } + + private System.Runtime.Serialization.ISurrogateSelector surrogateSelector; + public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector + { + get { return surrogateSelector; } + set { surrogateSelector = value; } + } + } +#endif + +#if DEBUG // this is used by some unit tests only, to ensure no buffering when buffering is disabled + private bool forwardsOnly; + /// + /// If true, buffering of nested objects is disabled + /// + public bool ForwardsOnly + { + get { return forwardsOnly; } + set { forwardsOnly = value; } + } +#endif + + internal virtual Type GetType(string fullName, Assembly context) + { + return ResolveKnownType(fullName, this, context); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + internal static Type ResolveKnownType(string name, TypeModel model, Assembly assembly) + { + if (string.IsNullOrEmpty(name)) return null; + try + { + Type type = Type.GetType(name); + + if (type != null) return type; + } + catch { } + try + { + int i = name.IndexOf(','); + string fullName = (i > 0 ? name.Substring(0, i) : name).Trim(); +#if !(COREFX || PROFILE259) + if (assembly == null) assembly = Assembly.GetCallingAssembly(); +#endif + Type type = assembly?.GetType(fullName); + if (type != null) return type; + } + catch { } + return null; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta new file mode 100644 index 00000000..cc869c39 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/TypeModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e5eb182ec8bc8c5469c7819c0e3f7fb4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ValueMember.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ValueMember.cs new file mode 100644 index 00000000..9566312c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ValueMember.cs @@ -0,0 +1,855 @@ +#if !NO_RUNTIME +using System; + +using ProtoBuf.Serializers; +using System.Globalization; +using System.Collections.Generic; + +#if PROFILE259 +using System.Reflection; +using System.Linq; +#else +using System.Reflection; +#endif + +namespace ProtoBuf.Meta +{ + /// + /// Represents a member (property/field) that is mapped to a protobuf field + /// + public class ValueMember + { + private int _fieldNumber; + /// + /// The number that identifies this member in a protobuf stream + /// + public int FieldNumber + { + get => _fieldNumber; + internal set + { + if (_fieldNumber != value) + { + MetaType.AssertValidFieldNumber(value); + ThrowIfFrozen(); + _fieldNumber = value; + } + } + } + + private readonly MemberInfo originalMember; + private MemberInfo backingMember; + /// + /// Gets the member (field/property) which this member relates to. + /// + public MemberInfo Member { get { return originalMember; } } + /// + /// Gets the backing member (field/property) which this member relates to + /// + public MemberInfo BackingMember + { + get { return backingMember; } + set + { + if (backingMember != value) + { + ThrowIfFrozen(); + backingMember = value; + } + } + } + + private readonly Type parentType, itemType, defaultType, memberType; + private object defaultValue; + + /// + /// Within a list / array / etc, the type of object for each item in the list (especially useful with ArrayList) + /// + public Type ItemType => itemType; + + /// + /// The underlying type of the member + /// + public Type MemberType => memberType; + + /// + /// For abstract types (IList etc), the type of concrete object to create (if required) + /// + public Type DefaultType => defaultType; + + /// + /// The type the defines the member + /// + public Type ParentType => parentType; + + /// + /// The default value of the item (members with this value will not be serialized) + /// + public object DefaultValue + { + get { return defaultValue; } + set + { + if (defaultValue != value) + { + ThrowIfFrozen(); + defaultValue = value; + } + } + } + + private readonly RuntimeTypeModel model; + /// + /// Creates a new ValueMember instance + /// + public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) + : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat) + { + if (parentType == null) throw new ArgumentNullException("parentType"); + if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber"); + + this.originalMember = member ?? throw new ArgumentNullException("member"); + this.parentType = parentType; + if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) throw new ArgumentOutOfRangeException("fieldNumber"); + //#if WINRT + if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType) + //#else + // if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue)) + //#endif + { + defaultValue = ParseDefaultValue(memberType, defaultValue); + } + this.defaultValue = defaultValue; + + MetaType type = model.FindWithoutAdd(memberType); + if (type != null) + { + AsReference = type.AsReferenceDefault; + } + else + { // we need to scan the hard way; can't risk recursion by fully walking it + AsReference = MetaType.GetAsReferenceDefault(model, memberType); + } + } + /// + /// Creates a new ValueMember instance + /// + internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat) + { + _fieldNumber = fieldNumber; + this.memberType = memberType ?? throw new ArgumentNullException(nameof(memberType)); + this.itemType = itemType; + this.defaultType = defaultType; + + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.dataFormat = dataFormat; + } + internal object GetRawEnumValue() + { +#if PORTABLE || CF || COREFX || PROFILE259 + object value = ((FieldInfo)originalMember).GetValue(null); + switch(Helpers.GetTypeCode(Enum.GetUnderlyingType(((FieldInfo)originalMember).FieldType))) + { + case ProtoTypeCode.SByte: return (sbyte)value; + case ProtoTypeCode.Byte: return (byte)value; + case ProtoTypeCode.Int16: return (short)value; + case ProtoTypeCode.UInt16: return (ushort)value; + case ProtoTypeCode.Int32: return (int)value; + case ProtoTypeCode.UInt32: return (uint)value; + case ProtoTypeCode.Int64: return (long)value; + case ProtoTypeCode.UInt64: return (ulong)value; + default: + throw new InvalidOperationException(); + } +#else + return ((FieldInfo)originalMember).GetRawConstantValue(); +#endif + } + private static object ParseDefaultValue(Type type, object value) + { + { + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + } + if (value is string s) + { + if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s); + + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: return bool.Parse(s); + case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); + case ProtoTypeCode.Char: // char.Parse missing on CF/phone7 + if (s.Length == 1) return s[0]; + throw new FormatException("Single character expected: \"" + s + "\""); + case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture); + case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); + case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.String: return s; + case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture); + case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s); + case ProtoTypeCode.Uri: return s; // Uri is decorated as string + case ProtoTypeCode.Guid: return new Guid(s); + } + } + + if (Helpers.IsEnum(type)) return Enum.ToObject(type, value); + return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + + } + + private IProtoSerializer serializer; + internal IProtoSerializer Serializer + { + get + { + return serializer ?? (serializer = BuildSerializer()); + } + } + + private DataFormat dataFormat; + /// + /// Specifies the rules used to process the field; this is used to determine the most appropriate + /// wite-type, but also to describe subtypes within that wire-type (such as SignedVariant) + /// + public DataFormat DataFormat + { + get { return dataFormat; } + set + { + if (value != dataFormat) + { + ThrowIfFrozen(); + this.dataFormat = value; + } + } + } + + /// + /// Indicates whether this field should follow strict encoding rules; this means (for example) that if a "fixed32" + /// is encountered when "variant" is defined, then it will fail (throw an exception) when parsing. Note that + /// when serializing the defined type is always used. + /// + public bool IsStrict + { + get { return HasFlag(OPTIONS_IsStrict); } + set { SetFlag(OPTIONS_IsStrict, value, true); } + } + + /// + /// Indicates whether this field should use packed encoding (which can save lots of space for repeated primitive values). + /// This option only applies to list/array data of primitive types (int, double, etc). + /// + public bool IsPacked + { + get { return HasFlag(OPTIONS_IsPacked); } + set { SetFlag(OPTIONS_IsPacked, value, true); } + } + + /// + /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*). + /// This option only applies to list/array data. + /// + public bool OverwriteList + { + get { return HasFlag(OPTIONS_OverwriteList); } + set { SetFlag(OPTIONS_OverwriteList, value, true); } + } + + /// + /// Indicates whether this field is mandatory. + /// + public bool IsRequired + { + get { return HasFlag(OPTIONS_IsRequired); } + set { SetFlag(OPTIONS_IsRequired, value, true); } + } + + /// + /// Enables full object-tracking/full-graph support. + /// + public bool AsReference + { + get { return HasFlag(OPTIONS_AsReference); } + set { SetFlag(OPTIONS_AsReference, value, true); } + } + + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance. + /// + public bool DynamicType + { + get { return HasFlag(OPTIONS_DynamicType); } + set { SetFlag(OPTIONS_DynamicType, value, true); } + } + + /// + /// Indicates that the member should be treated as a protobuf Map + /// + public bool IsMap + { + get { return HasFlag(OPTIONS_IsMap); } + set { SetFlag(OPTIONS_IsMap, value, true); } + } + + private DataFormat mapKeyFormat, mapValueFormat; + /// + /// Specifies the data-format that should be used for the key, when IsMap is enabled + /// + public DataFormat MapKeyFormat + { + get { return mapKeyFormat; } + set + { + if (mapKeyFormat != value) + { + ThrowIfFrozen(); + mapKeyFormat = value; + } + } + } + /// + /// Specifies the data-format that should be used for the value, when IsMap is enabled + /// + public DataFormat MapValueFormat + { + get { return mapValueFormat; } + set + { + if (mapValueFormat != value) + { + ThrowIfFrozen(); + mapValueFormat = value; + } + } + } + + private MethodInfo getSpecified, setSpecified; + /// + /// Specifies methods for working with optional data members. + /// + /// Provides a method (null for none) to query whether this member should + /// be serialized; it must be of the form "bool {Method}()". The member is only serialized if the + /// method returns true. + /// Provides a method (null for none) to indicate that a member was + /// deserialized; it must be of the form "void {Method}(bool)", and will be called with "true" + /// when data is found. + public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified) + { + if (this.getSpecified != getSpecified || this.setSpecified != setSpecified) + { + if (getSpecified != null) + { + if (getSpecified.ReturnType != model.MapType(typeof(bool)) + || getSpecified.IsStatic + || getSpecified.GetParameters().Length != 0) + { + throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified"); + } + } + if (setSpecified != null) + { + ParameterInfo[] args; + if (setSpecified.ReturnType != model.MapType(typeof(void)) + || setSpecified.IsStatic + || (args = setSpecified.GetParameters()).Length != 1 + || args[0].ParameterType != model.MapType(typeof(bool))) + { + throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified"); + } + } + + ThrowIfFrozen(); + this.getSpecified = getSpecified; + this.setSpecified = setSpecified; + } + } + + private void ThrowIfFrozen() + { + if (serializer != null) throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); + } + + internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType) + { + dictionaryType = keyType = valueType = null; + try + { +#if COREFX || PROFILE259 + var info = memberType.GetTypeInfo(); +#else + var info = memberType; +#endif + if (ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out _, out _, out _, out _, out _, out _)) + { + return false; + } + if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { +#if PROFILE259 + var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments; +#else + var typeArgs = memberType.GetGenericArguments(); +#endif + if (IsValidMapKeyType(typeArgs[0])) + { + keyType = typeArgs[0]; + valueType = typeArgs[1]; + dictionaryType = memberType; + } + return false; + } +#if PROFILE259 + foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces) +#else + foreach (var iType in memberType.GetInterfaces()) +#endif + { +#if COREFX || PROFILE259 + info = iType.GetTypeInfo(); +#else + info = iType; +#endif + if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { + if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName); +#if PROFILE259 + var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments; +#else + var typeArgs = iType.GetGenericArguments(); +#endif + if (IsValidMapKeyType(typeArgs[0])) + { + keyType = typeArgs[0]; + valueType = typeArgs[1]; + dictionaryType = memberType; + } + } + } + if (dictionaryType == null) return false; + + // (note we checked the key type already) + // not a map if value is repeated + Type itemType = null, defaultType = null; + model.ResolveListTypes(valueType, ref itemType, ref defaultType); + if (itemType != null) return false; + + return dictionaryType != null; + } + catch + { + // if it isn't a good fit; don't use "map" + return false; + } + } + + static bool IsValidMapKeyType(Type type) + { + if (type == null || Helpers.IsEnum(type)) return false; + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.Int64: + case ProtoTypeCode.String: + + case ProtoTypeCode.SByte: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.UInt64: + return true; + } + return false; + } + private IProtoSerializer BuildSerializer() + { + int opaqueToken = 0; + try + { + model.TakeLock(ref opaqueToken);// check nobody is still adding this type + var member = backingMember ?? originalMember; + IProtoSerializer ser; + if (IsMap) + { + ResolveMapTypes(out var dictionaryType, out var keyType, out var valueType); + + if (dictionaryType == null) + { + throw new InvalidOperationException("Unable to resolve map type for type: " + memberType.FullName); + } + var concreteType = defaultType; + if (concreteType == null && Helpers.IsClass(memberType)) + { + concreteType = memberType; + } + var keySer = TryGetCoreSerializer(model, MapKeyFormat, keyType, out var keyWireType, false, false, false, false); + if (!AsReference) + { + AsReference = MetaType.GetAsReferenceDefault(model, valueType); + } + var valueSer = TryGetCoreSerializer(model, MapValueFormat, valueType, out var valueWireType, AsReference, DynamicType, false, true); +#if PROFILE259 + IEnumerable ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetTypeInfo().DeclaredConstructors; + if (ctors.Count() != 1) + { + throw new InvalidOperationException("Unable to resolve MapDecorator constructor"); + } + ser = (IProtoSerializer)ctors.First().Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber, + DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList }); +#else + var ctors = typeof(MapDecorator<,,>).MakeGenericType(new Type[] { dictionaryType, keyType, valueType }).GetConstructors( + BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + if (ctors.Length != 1) throw new InvalidOperationException("Unable to resolve MapDecorator constructor"); + ser = (IProtoSerializer)ctors[0].Invoke(new object[] {model, concreteType, keySer, valueSer, _fieldNumber, + DataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String, keyWireType, valueWireType, OverwriteList }); +#endif + } + else + { + Type finalType = itemType ?? memberType; + ser = TryGetCoreSerializer(model, dataFormat, finalType, out WireType wireType, AsReference, DynamicType, OverwriteList, true); + if (ser == null) + { + throw new InvalidOperationException("No serializer defined for type: " + finalType.FullName); + } + + // apply tags + if (itemType != null && SupportNull) + { + if (IsPacked) + { + throw new NotSupportedException("Packed encodings cannot support null values"); + } + ser = new TagDecorator(NullDecorator.Tag, wireType, IsStrict, ser); + ser = new NullDecorator(model, ser); + ser = new TagDecorator(_fieldNumber, WireType.StartGroup, false, ser); + } + else + { + ser = new TagDecorator(_fieldNumber, wireType, IsStrict, ser); + } + // apply lists if appropriate + if (itemType != null) + { + Type underlyingItemType = SupportNull ? itemType : Helpers.GetUnderlyingType(itemType) ?? itemType; + + Helpers.DebugAssert(underlyingItemType == ser.ExpectedType + || (ser.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType)) + , "Wrong type in the tail; expected {0}, received {1}", ser.ExpectedType, underlyingItemType); + if (memberType.IsArray) + { + ser = new ArrayDecorator(model, ser, _fieldNumber, IsPacked, wireType, memberType, OverwriteList, SupportNull); + } + else + { + ser = ListDecorator.Create(model, memberType, defaultType, ser, _fieldNumber, IsPacked, wireType, member != null && PropertyDecorator.CanWrite(model, member), OverwriteList, SupportNull); + } + } + else if (defaultValue != null && !IsRequired && getSpecified == null) + { // note: "ShouldSerialize*" / "*Specified" / etc ^^^^ take precedence over defaultValue, + // as does "IsRequired" + ser = new DefaultValueDecorator(model, defaultValue, ser); + } + if (memberType == model.MapType(typeof(Uri))) + { + ser = new UriDecorator(model, ser); + } +#if PORTABLE + else if(memberType.FullName == typeof(Uri).FullName) + { + // In PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri) + ser = new ReflectedUriDecorator(memberType, model, ser); + } +#endif + } + if (member != null) + { + if (member is PropertyInfo prop) + { + ser = new PropertyDecorator(model, parentType, prop, ser); + } + else if (member is FieldInfo fld) + { + ser = new FieldDecorator(parentType, fld, ser); + } + else + { + throw new InvalidOperationException(); + } + + if (getSpecified != null || setSpecified != null) + { + ser = new MemberSpecifiedDecorator(getSpecified, setSpecified, ser); + } + } + return ser; + } + finally + { + model.ReleaseLock(opaqueToken); + } + } + + private static WireType GetIntWireType(DataFormat format, int width) + { + switch (format) + { + case DataFormat.ZigZag: return WireType.SignedVariant; + case DataFormat.FixedSize: return width == 32 ? WireType.Fixed32 : WireType.Fixed64; + case DataFormat.TwosComplement: + case DataFormat.Default: return WireType.Variant; + default: throw new InvalidOperationException(); + } + } + private static WireType GetDateTimeWireType(DataFormat format) + { + switch (format) + { + + case DataFormat.Group: return WireType.StartGroup; + case DataFormat.FixedSize: return WireType.Fixed64; + case DataFormat.WellKnown: + case DataFormat.Default: + return WireType.String; + default: throw new InvalidOperationException(); + } + } + + internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, + bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) + { + { + Type tmp = Helpers.GetUnderlyingType(type); + if (tmp != null) type = tmp; + } + if (Helpers.IsEnum(type)) + { + if (allowComplexTypes && model != null) + { + // need to do this before checking the typecode; an int enum will report Int32 etc + defaultWireType = WireType.Variant; + return new EnumSerializer(type, model.GetEnumMap(type)); + } + else + { // enum is fine for adding as a meta-type + defaultWireType = WireType.None; + return null; + } + } + ProtoTypeCode code = Helpers.GetTypeCode(type); + switch (code) + { + case ProtoTypeCode.Int32: + defaultWireType = GetIntWireType(dataFormat, 32); + return new Int32Serializer(model); + case ProtoTypeCode.UInt32: + defaultWireType = GetIntWireType(dataFormat, 32); + return new UInt32Serializer(model); + case ProtoTypeCode.Int64: + defaultWireType = GetIntWireType(dataFormat, 64); + return new Int64Serializer(model); + case ProtoTypeCode.UInt64: + defaultWireType = GetIntWireType(dataFormat, 64); + return new UInt64Serializer(model); + case ProtoTypeCode.String: + defaultWireType = WireType.String; + if (asReference) + { + return new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference); + } + return new StringSerializer(model); + case ProtoTypeCode.Single: + defaultWireType = WireType.Fixed32; + return new SingleSerializer(model); + case ProtoTypeCode.Double: + defaultWireType = WireType.Fixed64; + return new DoubleSerializer(model); + case ProtoTypeCode.Boolean: + defaultWireType = WireType.Variant; + return new BooleanSerializer(model); + case ProtoTypeCode.DateTime: + defaultWireType = GetDateTimeWireType(dataFormat); + return new DateTimeSerializer(dataFormat, model); + case ProtoTypeCode.Decimal: + defaultWireType = WireType.String; + return new DecimalSerializer(model); + case ProtoTypeCode.Byte: + defaultWireType = GetIntWireType(dataFormat, 32); + return new ByteSerializer(model); + case ProtoTypeCode.SByte: + defaultWireType = GetIntWireType(dataFormat, 32); + return new SByteSerializer(model); + case ProtoTypeCode.Char: + defaultWireType = WireType.Variant; + return new CharSerializer(model); + case ProtoTypeCode.Int16: + defaultWireType = GetIntWireType(dataFormat, 32); + return new Int16Serializer(model); + case ProtoTypeCode.UInt16: + defaultWireType = GetIntWireType(dataFormat, 32); + return new UInt16Serializer(model); + case ProtoTypeCode.TimeSpan: + defaultWireType = GetDateTimeWireType(dataFormat); + return new TimeSpanSerializer(dataFormat, model); + case ProtoTypeCode.Guid: + defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; + return new GuidSerializer(model); + case ProtoTypeCode.Uri: + defaultWireType = WireType.String; + return new StringSerializer(model); + case ProtoTypeCode.ByteArray: + defaultWireType = WireType.String; + return new BlobSerializer(model, overwriteList); + case ProtoTypeCode.Type: + defaultWireType = WireType.String; + return new SystemTypeSerializer(model); + } + IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null; + if (parseable != null) + { + defaultWireType = WireType.String; + return parseable; + } + if (allowComplexTypes && model != null) + { + int key = model.GetKey(type, false, true); + MetaType meta = null; + if (key >= 0) + { + meta = model[type]; + if (dataFormat == DataFormat.Default && meta.IsGroup) + { + dataFormat = DataFormat.Group; + } + } + + if (asReference || dynamicType) + { + BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None; + if (asReference) options |= BclHelpers.NetObjectOptions.AsReference; + if (dynamicType) options |= BclHelpers.NetObjectOptions.DynamicType; + if (meta != null) + { // exists + if (asReference && Helpers.IsValueType(type)) + { + string message = "AsReference cannot be used with value-types"; + + if (type.Name == "KeyValuePair`2") + { + message += "; please see https://stackoverflow.com/q/14436606/23354"; + } + else + { + message += ": " + type.FullName; + } + throw new InvalidOperationException(message); + } + + if (asReference && meta.IsAutoTuple) options |= BclHelpers.NetObjectOptions.LateSet; + if (meta.UseConstructor) options |= BclHelpers.NetObjectOptions.UseConstructor; + } + defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; + return new NetObjectSerializer(model, type, key, options); + } + if (key >= 0) + { + defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; + return new SubItemSerializer(type, key, meta, true); + } + } + defaultWireType = WireType.None; + return null; + } + + + private string name; + internal void SetName(string name) + { + if (name != this.name) + { + ThrowIfFrozen(); + this.name = name; + } + } + /// + /// Gets the logical name for this member in the schema (this is not critical for binary serialization, but may be used + /// when inferring a schema). + /// + public string Name + { + get { return string.IsNullOrEmpty(name) ? originalMember.Name : name; } + set { SetName(value); } + } + + private const byte + OPTIONS_IsStrict = 1, + OPTIONS_IsPacked = 2, + OPTIONS_IsRequired = 4, + OPTIONS_OverwriteList = 8, + OPTIONS_SupportNull = 16, + OPTIONS_AsReference = 32, + OPTIONS_IsMap = 64, + OPTIONS_DynamicType = 128; + + private byte flags; + private bool HasFlag(byte flag) { return (flags & flag) == flag; } + private void SetFlag(byte flag, bool value, bool throwIfFrozen) + { + if (throwIfFrozen && HasFlag(flag) != value) + { + ThrowIfFrozen(); + } + if (value) + flags |= flag; + else + flags = (byte)(flags & ~flag); + } + + /// + /// Should lists have extended support for null values? Note this makes the serialization less efficient. + /// + public bool SupportNull + { + get { return HasFlag(OPTIONS_SupportNull); } + set { SetFlag(OPTIONS_SupportNull, value, true); } + } + + internal string GetSchemaTypeName(bool applyNetObjectProxy, ref RuntimeTypeModel.CommonImports imports) + { + Type effectiveType = ItemType; + if (effectiveType == null) effectiveType = MemberType; + return model.GetSchemaTypeName(effectiveType, DataFormat, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, ref imports); + } + + + internal sealed class Comparer : System.Collections.IComparer, IComparer + { + public static readonly Comparer Default = new Comparer(); + + public int Compare(object x, object y) + { + return Compare(x as ValueMember, y as ValueMember); + } + + public int Compare(ValueMember x, ValueMember y) + { + if (ReferenceEquals(x, y)) return 0; + if (x == null) return -1; + if (y == null) return 1; + + return x.FieldNumber.CompareTo(y.FieldNumber); + } + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta new file mode 100644 index 00000000..d3eeb789 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Meta/ValueMember.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dba7fd2d1d1c883469e153f7ac5fdd86 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/NetObjectCache.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/NetObjectCache.cs new file mode 100644 index 00000000..8e83549a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/NetObjectCache.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + internal sealed class NetObjectCache + { + internal const int Root = 0; + private MutableList underlyingList; + + private MutableList List => underlyingList ?? (underlyingList = new MutableList()); + + internal object GetKeyedObject(int key) + { + if (key-- == Root) + { + if (rootObject == null) throw new ProtoException("No root object assigned"); + return rootObject; + } + BasicList list = List; + + if (key < 0 || key >= list.Count) + { + Helpers.DebugWriteLine("Missing key: " + key); + throw new ProtoException("Internal error; a missing key occurred"); + } + + object tmp = list[key]; + if (tmp == null) + { + throw new ProtoException("A deferred key does not have a value yet"); + } + return tmp; + } + + internal void SetKeyedObject(int key, object value) + { + if (key-- == Root) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + if (rootObject != null && ((object)rootObject != (object)value)) throw new ProtoException("The root object cannot be reassigned"); + rootObject = value; + } + else + { + MutableList list = List; + if (key < list.Count) + { + object oldVal = list[key]; + if (oldVal == null) + { + list[key] = value; + } + else if (!ReferenceEquals(oldVal, value)) + { + throw new ProtoException("Reference-tracked objects cannot change reference"); + } // otherwise was the same; nothing to do + } + else if (key != list.Add(value)) + { + throw new ProtoException("Internal error; a key mismatch occurred"); + } + } + } + + private object rootObject; + internal int AddObjectKey(object value, out bool existing) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + + if ((object)value == (object)rootObject) // (object) here is no-op, but should be + { // preserved even if this was typed - needs ref-check + existing = true; + return Root; + } + + string s = value as string; + BasicList list = List; + int index; + + if (s == null) + { +#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way + index = list.IndexOfReference(value); +#else + if (objectKeys == null) + { + objectKeys = new Dictionary(ReferenceComparer.Default); + index = -1; + } + else + { + if (!objectKeys.TryGetValue(value, out index)) index = -1; + } +#endif + } + else + { + if (stringKeys == null) + { + stringKeys = new Dictionary(); + index = -1; + } + else + { + if (!stringKeys.TryGetValue(s, out index)) index = -1; + } + } + + if (!(existing = index >= 0)) + { + index = list.Add(value); + + if (s == null) + { +#if !CF && !PORTABLE // CF can't handle the object keys very well + objectKeys.Add(value, index); +#endif + } + else + { + stringKeys.Add(s, index); + } + } + return index + 1; + } + + private int trapStartIndex; // defaults to 0 - optimization for RegisterTrappedObject + // to make it faster at seeking to find deferred-objects + + internal void RegisterTrappedObject(object value) + { + if (rootObject == null) + { + rootObject = value; + } + else + { + if (underlyingList != null) + { + for (int i = trapStartIndex; i < underlyingList.Count; i++) + { + trapStartIndex = i + 1; // things never *become* null; whether or + // not the next item is null, it will never + // need to be checked again + + if (underlyingList[i] == null) + { + underlyingList[i] = value; + break; + } + } + } + } + } + + private Dictionary stringKeys; + +#if !CF && !PORTABLE // CF lacks the ability to get a robust reference-based hash-code, so we'll do it the harder way instead + private System.Collections.Generic.Dictionary objectKeys; + private sealed class ReferenceComparer : IEqualityComparer + { + public readonly static ReferenceComparer Default = new ReferenceComparer(); + private ReferenceComparer() { } + + bool IEqualityComparer.Equals(object x, object y) + { + return x == y; // ref equality + } + + int IEqualityComparer.GetHashCode(object obj) + { + return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); + } + } +#endif + + internal void Clear() + { + trapStartIndex = 0; + rootObject = null; + if (underlyingList != null) underlyingList.Clear(); + if (stringKeys != null) stringKeys.Clear(); +#if !CF && !PORTABLE + if (objectKeys != null) objectKeys.Clear(); +#endif + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/NetObjectCache.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/NetObjectCache.cs.meta new file mode 100644 index 00000000..862acc01 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/NetObjectCache.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a7ec59f6037764d43b3d585baf2343e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/PrefixStyle.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/PrefixStyle.cs new file mode 100644 index 00000000..0ebef04f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/PrefixStyle.cs @@ -0,0 +1,26 @@ + +namespace ProtoBuf +{ + /// + /// Specifies the type of prefix that should be applied to messages. + /// + public enum PrefixStyle + { + /// + /// No length prefix is applied to the data; the data is terminated only be the end of the stream. + /// + None = 0, + /// + /// A base-128 ("varint", the default prefix format in protobuf) length prefix is applied to the data (efficient for short messages). + /// + Base128 = 1, + /// + /// A fixed-length (little-endian) length prefix is applied to the data (useful for compatibility). + /// + Fixed32 = 2, + /// + /// A fixed-length (big-endian) length prefix is applied to the data (useful for compatibility). + /// + Fixed32BigEndian = 3 + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/PrefixStyle.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/PrefixStyle.cs.meta new file mode 100644 index 00000000..a955c1fb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/PrefixStyle.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6f16948bce1f2d4eb805ed31a2bb878 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoContractAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoContractAttribute.cs new file mode 100644 index 00000000..e2e8054a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoContractAttribute.cs @@ -0,0 +1,175 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Indicates that a type is defined for protocol-buffer serialization. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, + AllowMultiple = false, Inherited = false)] + public sealed class ProtoContractAttribute : Attribute + { + /// + /// Gets or sets the defined name of the type. + /// + public string Name { get; set; } + + /// + /// Gets or sets the fist offset to use with implicit field tags; + /// only uesd if ImplicitFields is set. + /// + public int ImplicitFirstTag + { + get { return implicitFirstTag; } + set + { + if (value < 1) throw new ArgumentOutOfRangeException("ImplicitFirstTag"); + implicitFirstTag = value; + } + } + private int implicitFirstTag; + + /// + /// If specified, alternative contract markers (such as markers for XmlSerailizer or DataContractSerializer) are ignored. + /// + public bool UseProtoMembersOnly + { + get { return HasFlag(OPTIONS_UseProtoMembersOnly); } + set { SetFlag(OPTIONS_UseProtoMembersOnly, value); } + } + + /// + /// If specified, do NOT treat this type as a list, even if it looks like one. + /// + public bool IgnoreListHandling + { + get { return HasFlag(OPTIONS_IgnoreListHandling); } + set { SetFlag(OPTIONS_IgnoreListHandling, value); } + } + + /// + /// Gets or sets the mechanism used to automatically infer field tags + /// for members. This option should be used in advanced scenarios only. + /// Please review the important notes against the ImplicitFields enumeration. + /// + public ImplicitFields ImplicitFields { get; set; } + + /// + /// Enables/disables automatic tag generation based on the existing name / order + /// of the defined members. This option is not used for members marked + /// with ProtoMemberAttribute, as intended to provide compatibility with + /// WCF serialization. WARNING: when adding new fields you must take + /// care to increase the Order for new elements, otherwise data corruption + /// may occur. + /// + /// If not explicitly specified, the default is assumed from Serializer.GlobalOptions.InferTagFromName. + public bool InferTagFromName + { + get { return HasFlag(OPTIONS_InferTagFromName); } + set + { + SetFlag(OPTIONS_InferTagFromName, value); + SetFlag(OPTIONS_InferTagFromNameHasValue, true); + } + } + + /// + /// Has a InferTagFromName value been explicitly set? if not, the default from the type-model is assumed. + /// + internal bool InferTagFromNameHasValue + { // note that this property is accessed via reflection and should not be removed + get { return HasFlag(OPTIONS_InferTagFromNameHasValue); } + } + + /// + /// Specifies an offset to apply to [DataMember(Order=...)] markers; + /// this is useful when working with mex-generated classes that have + /// a different origin (usually 1 vs 0) than the original data-contract. + /// + /// This value is added to the Order of each member. + /// + public int DataMemberOffset { get; set; } + + /// + /// If true, the constructor for the type is bypassed during deserialization, meaning any field initializers + /// or other initialization code is skipped. + /// + public bool SkipConstructor + { + get { return HasFlag(OPTIONS_SkipConstructor); } + set { SetFlag(OPTIONS_SkipConstructor, value); } + } + + /// + /// Should this type be treated as a reference by default? Please also see the implications of this, + /// as recorded on ProtoMemberAttribute.AsReference + /// + public bool AsReferenceDefault + { + get { return HasFlag(OPTIONS_AsReferenceDefault); } + set + { + SetFlag(OPTIONS_AsReferenceDefault, value); + } + } + + /// + /// Indicates whether this type should always be treated as a "group" (rather than a string-prefixed sub-message) + /// + public bool IsGroup + { + get { return HasFlag(OPTIONS_IsGroup); } + set + { + SetFlag(OPTIONS_IsGroup, value); + } + } + + private bool HasFlag(ushort flag) { return (flags & flag) == flag; } + private void SetFlag(ushort flag, bool value) + { + if (value) flags |= flag; + else flags = (ushort)(flags & ~flag); + } + + private ushort flags; + + private const ushort + OPTIONS_InferTagFromName = 1, + OPTIONS_InferTagFromNameHasValue = 2, + OPTIONS_UseProtoMembersOnly = 4, + OPTIONS_SkipConstructor = 8, + OPTIONS_IgnoreListHandling = 16, + OPTIONS_AsReferenceDefault = 32, + OPTIONS_EnumPassthru = 64, + OPTIONS_EnumPassthruHasValue = 128, + OPTIONS_IsGroup = 256; + + /// + /// Applies only to enums (not to DTO classes themselves); gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather + /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums. + /// + public bool EnumPassthru + { + get { return HasFlag(OPTIONS_EnumPassthru); } + set + { + SetFlag(OPTIONS_EnumPassthru, value); + SetFlag(OPTIONS_EnumPassthruHasValue, true); + } + } + + /// + /// Allows to define a surrogate type used for serialization/deserialization purpose. + /// + public Type Surrogate { get; set; } + + /// + /// Has a EnumPassthru value been explicitly set? + /// + internal bool EnumPassthruHasValue + { // note that this property is accessed via reflection and should not be removed + get { return HasFlag(OPTIONS_EnumPassthruHasValue); } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta new file mode 100644 index 00000000..d0006881 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoContractAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e5d57dba877f0854c999b91a6514d93d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoConverterAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoConverterAttribute.cs new file mode 100644 index 00000000..b75bb803 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoConverterAttribute.cs @@ -0,0 +1,13 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Indicates that a static member should be considered the same as though + /// were an implicit / explicit conversion operator; in particular, this + /// is useful for conversions that operator syntax does not allow, such as + /// to/from interface types. + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + public class ProtoConverterAttribute : Attribute { } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta new file mode 100644 index 00000000..323a3a46 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoConverterAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 399681000a748834f87d721feda5f459 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoEnumAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoEnumAttribute.cs new file mode 100644 index 00000000..1d826454 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoEnumAttribute.cs @@ -0,0 +1,36 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Used to define protocol-buffer specific behavior for + /// enumerated values. + /// + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] + public sealed class ProtoEnumAttribute : Attribute + { + /// + /// Gets or sets the specific value to use for this enum during serialization. + /// + public int Value + { + get { return enumValue; } + set { this.enumValue = value; hasValue = true; } + } + + /// + /// Indicates whether this instance has a customised value mapping + /// + /// true if a specific value is set + public bool HasValue() => hasValue; + + private bool hasValue; + private int enumValue; + + /// + /// Gets or sets the defined name of the enum, as used in .proto + /// (this name is not used during serialization). + /// + public string Name { get; set; } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta new file mode 100644 index 00000000..a5cada98 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoEnumAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b3e030ed91e74b49b87bb0cd9acf139 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoException.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoException.cs new file mode 100644 index 00000000..f502527b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoException.cs @@ -0,0 +1,30 @@ +using System; + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) +using System.Runtime.Serialization; +#endif +namespace ProtoBuf +{ + /// + /// Indicates an error during serialization/deserialization of a proto stream. + /// +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + [Serializable] +#endif + public class ProtoException : Exception + { + /// Creates a new ProtoException instance. + public ProtoException() { } + + /// Creates a new ProtoException instance. + public ProtoException(string message) : base(message) { } + + /// Creates a new ProtoException instance. + public ProtoException(string message, Exception innerException) : base(message, innerException) { } + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// Creates a new ProtoException instance. + protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoException.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoException.cs.meta new file mode 100644 index 00000000..28099e55 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8629683d41766534fa00bcb5d1a324e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs new file mode 100644 index 00000000..775674e9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs @@ -0,0 +1,40 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Indicates that a member should be excluded from serialization; this + /// is only normally used when using implict fields. + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, + AllowMultiple = false, Inherited = true)] + public class ProtoIgnoreAttribute : Attribute { } + + /// + /// Indicates that a member should be excluded from serialization; this + /// is only normally used when using implict fields. This allows + /// ProtoIgnoreAttribute usage + /// even for partial classes where the individual members are not + /// under direct control. + /// + [AttributeUsage(AttributeTargets.Class, + AllowMultiple = true, Inherited = false)] + public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute + { + /// + /// Creates a new ProtoPartialIgnoreAttribute instance. + /// + /// Specifies the member to be ignored. + public ProtoPartialIgnoreAttribute(string memberName) + : base() + { + if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName)); + + MemberName = memberName; + } + /// + /// The name of the member to be ignored. + /// + public string MemberName { get; } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta new file mode 100644 index 00000000..00afe26e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIgnoreAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b012b09d39a7c2445aba79ffee82b117 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs new file mode 100644 index 00000000..bb83ef78 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs @@ -0,0 +1,60 @@ +using System; +using System.ComponentModel; + +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// Indicates the known-types to support for an individual + /// message. This serializes each level in the hierarchy as + /// a nested message to retain wire-compatibility with + /// other protocol-buffer implementations. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] + public sealed class ProtoIncludeAttribute : Attribute + { + /// + /// Creates a new instance of the ProtoIncludeAttribute. + /// + /// The unique index (within the type) that will identify this data. + /// The additional type to serialize/deserialize. + public ProtoIncludeAttribute(int tag, Type knownType) + : this(tag, knownType == null ? "" : knownType.AssemblyQualifiedName) { } + + /// + /// Creates a new instance of the ProtoIncludeAttribute. + /// + /// The unique index (within the type) that will identify this data. + /// The additional type to serialize/deserialize. + public ProtoIncludeAttribute(int tag, string knownTypeName) + { + if (tag <= 0) throw new ArgumentOutOfRangeException(nameof(tag), "Tags must be positive integers"); + if (string.IsNullOrEmpty(knownTypeName)) throw new ArgumentNullException(nameof(knownTypeName), "Known type cannot be blank"); + Tag = tag; + KnownTypeName = knownTypeName; + } + + /// + /// Gets the unique index (within the type) that will identify this data. + /// + public int Tag { get; } + + /// + /// Gets the additional type to serialize/deserialize. + /// + public string KnownTypeName { get; } + + /// + /// Gets the additional type to serialize/deserialize. + /// + public Type KnownType => TypeModel.ResolveKnownType(KnownTypeName, null, null); + + /// + /// Specifies whether the inherited sype's sub-message should be + /// written with a length-prefix (default), or with group markers. + /// + [DefaultValue(DataFormat.Default)] + public DataFormat DataFormat { get; set; } = DataFormat.Default; + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta new file mode 100644 index 00000000..edebcb5d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoIncludeAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 40d89f2230d5a4f4badf122df4ed9fae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMapAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMapAttribute.cs new file mode 100644 index 00000000..e85441a0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMapAttribute.cs @@ -0,0 +1,29 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Controls the formatting of elements in a dictionary, and indicates that + /// "map" rules should be used: duplicates *replace* earlier values, rather + /// than throwing an exception + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ProtoMapAttribute : Attribute + { + /// + /// Describes the data-format used to store the key + /// + public DataFormat KeyFormat { get; set; } + /// + /// Describes the data-format used to store the value + /// + public DataFormat ValueFormat { get; set; } + + /// + /// Disables "map" handling; dictionaries will use ".Add(key,value)" instead of "[key] = value", + /// which means duplicate keys will cause an exception (instead of retaining the final value); if + /// a proto schema is emitted, it will be produced using "repeated" instead of "map" + /// + public bool DisableMap { get; set; } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta new file mode 100644 index 00000000..cf765aef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMapAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d41a983b561e9043a8ce693aeb9c835 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMemberAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMemberAttribute.cs new file mode 100644 index 00000000..e5ab8962 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMemberAttribute.cs @@ -0,0 +1,228 @@ +using System; +using System.Reflection; + +namespace ProtoBuf +{ + /// + /// Declares a member to be used in protocol-buffer serialization, using + /// the given Tag. A DataFormat may be used to optimise the serialization + /// format (for instance, using zigzag encoding for negative numbers, or + /// fixed-length encoding for large values. + /// + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, + AllowMultiple = false, Inherited = true)] + public class ProtoMemberAttribute : Attribute + , IComparable + , IComparable + + { + /// + /// Compare with another ProtoMemberAttribute for sorting purposes + /// + public int CompareTo(object other) => CompareTo(other as ProtoMemberAttribute); + /// + /// Compare with another ProtoMemberAttribute for sorting purposes + /// + public int CompareTo(ProtoMemberAttribute other) + { + if (other == null) return -1; + if ((object)this == (object)other) return 0; + int result = this.tag.CompareTo(other.tag); + if (result == 0) result = string.CompareOrdinal(this.name, other.name); + return result; + } + + /// + /// Creates a new ProtoMemberAttribute instance. + /// + /// Specifies the unique tag used to identify this member within the type. + public ProtoMemberAttribute(int tag) : this(tag, false) + { } + + internal ProtoMemberAttribute(int tag, bool forced) + { + if (tag <= 0 && !forced) throw new ArgumentOutOfRangeException(nameof(tag)); + this.tag = tag; + } + +#if !NO_RUNTIME + internal MemberInfo Member, BackingMember; + internal bool TagIsPinned; +#endif + /// + /// Gets or sets the original name defined in the .proto; not used + /// during serialization. + /// + public string Name { get { return name; } set { name = value; } } + private string name; + + /// + /// Gets or sets the data-format to be used when encoding this value. + /// + public DataFormat DataFormat { get { return dataFormat; } set { dataFormat = value; } } + private DataFormat dataFormat; + + /// + /// Gets the unique tag used to identify this member within the type. + /// + public int Tag { get { return tag; } } + private int tag; + internal void Rebase(int tag) { this.tag = tag; } + + /// + /// Gets or sets a value indicating whether this member is mandatory. + /// + public bool IsRequired + { + get { return (options & MemberSerializationOptions.Required) == MemberSerializationOptions.Required; } + set + { + if (value) options |= MemberSerializationOptions.Required; + else options &= ~MemberSerializationOptions.Required; + } + } + + /// + /// Gets a value indicating whether this member is packed. + /// This option only applies to list/array data of primitive types (int, double, etc). + /// + public bool IsPacked + { + get { return (options & MemberSerializationOptions.Packed) == MemberSerializationOptions.Packed; } + set + { + if (value) options |= MemberSerializationOptions.Packed; + else options &= ~MemberSerializationOptions.Packed; + } + } + + /// + /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*). + /// This option only applies to list/array data. + /// + public bool OverwriteList + { + get { return (options & MemberSerializationOptions.OverwriteList) == MemberSerializationOptions.OverwriteList; } + set + { + if (value) options |= MemberSerializationOptions.OverwriteList; + else options &= ~MemberSerializationOptions.OverwriteList; + } + } + + /// + /// Enables full object-tracking/full-graph support. + /// + public bool AsReference + { + get { return (options & MemberSerializationOptions.AsReference) == MemberSerializationOptions.AsReference; } + set + { + if (value) options |= MemberSerializationOptions.AsReference; + else options &= ~MemberSerializationOptions.AsReference; + + options |= MemberSerializationOptions.AsReferenceHasValue; + } + } + + internal bool AsReferenceHasValue + { + get { return (options & MemberSerializationOptions.AsReferenceHasValue) == MemberSerializationOptions.AsReferenceHasValue; } + set + { + if (value) options |= MemberSerializationOptions.AsReferenceHasValue; + else options &= ~MemberSerializationOptions.AsReferenceHasValue; + } + } + + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance. + /// + public bool DynamicType + { + get { return (options & MemberSerializationOptions.DynamicType) == MemberSerializationOptions.DynamicType; } + set + { + if (value) options |= MemberSerializationOptions.DynamicType; + else options &= ~MemberSerializationOptions.DynamicType; + } + } + + /// + /// Gets or sets a value indicating whether this member is packed (lists/arrays). + /// + public MemberSerializationOptions Options { get { return options; } set { options = value; } } + private MemberSerializationOptions options; + + + } + + /// + /// Additional (optional) settings that control serialization of members + /// + [Flags] + public enum MemberSerializationOptions + { + /// + /// Default; no additional options + /// + None = 0, + /// + /// Indicates that repeated elements should use packed (length-prefixed) encoding + /// + Packed = 1, + /// + /// Indicates that the given item is required + /// + Required = 2, + /// + /// Enables full object-tracking/full-graph support + /// + AsReference = 4, + /// + /// Embeds the type information into the stream, allowing usage with types not known in advance + /// + DynamicType = 8, + /// + /// Indicates whether this field should *repace* existing values (the default is false, meaning *append*). + /// This option only applies to list/array data. + /// + OverwriteList = 16, + /// + /// Determines whether the types AsReferenceDefault value is used, or whether this member's AsReference should be used + /// + AsReferenceHasValue = 32 + } + + /// + /// Declares a member to be used in protocol-buffer serialization, using + /// the given Tag and MemberName. This allows ProtoMemberAttribute usage + /// even for partial classes where the individual members are not + /// under direct control. + /// A DataFormat may be used to optimise the serialization + /// format (for instance, using zigzag encoding for negative numbers, or + /// fixed-length encoding for large values. + /// + [AttributeUsage(AttributeTargets.Class, + AllowMultiple = true, Inherited = false)] + public sealed class ProtoPartialMemberAttribute : ProtoMemberAttribute + { + /// + /// Creates a new ProtoMemberAttribute instance. + /// + /// Specifies the unique tag used to identify this member within the type. + /// Specifies the member to be serialized. + public ProtoPartialMemberAttribute(int tag, string memberName) + : base(tag) + { +#if !NO_RUNTIME + if (string.IsNullOrEmpty(memberName)) throw new ArgumentNullException(nameof(memberName)); +#endif + this.MemberName = memberName; + } + /// + /// The name of the member to be serialized. + /// + public string MemberName { get; private set; } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta new file mode 100644 index 00000000..2f3dfc97 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoMemberAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 262c0823543b1b3499e2b67ca22f4e62 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoReader.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoReader.cs new file mode 100644 index 00000000..3ea9bf9e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoReader.cs @@ -0,0 +1,1444 @@ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// A stateful reader, used to read a protobuf stream. Typical usage would be (sequentially) to call + /// ReadFieldHeader and (after matching the field) an appropriate Read* method. + /// + public sealed class ProtoReader : IDisposable + { + Stream source; + byte[] ioBuffer; + TypeModel model; + int fieldNumber, depth, ioIndex, available; + long position64, blockEnd64, dataRemaining64; + WireType wireType; + bool isFixedLength, internStrings; + private NetObjectCache netCache; + + // this is how many outstanding objects do not currently have + // values for the purposes of reference tracking; we'll default + // to just trapping the root object + // note: objects are trapped (the ref and key mapped) via NoteObject + uint trapCount; // uint is so we can use beq/bne more efficiently than bgt + + /// + /// Gets the number of the field being processed. + /// + public int FieldNumber => fieldNumber; + + /// + /// Indicates the underlying proto serialization format on the wire. + /// + public WireType WireType => wireType; + + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context) + { + + Init(this, source, model, context, TO_EOF); + } + + internal const long TO_EOF = -1; + + /// + /// Gets / sets a flag indicating whether strings should be checked for repetition; if + /// true, any repeated UTF-8 byte sequence will result in the same String instance, rather + /// than a second instance of the same string. Enabled by default. Note that this uses + /// a custom interner - the system-wide string interner is not used. + /// + public bool InternStrings { get { return internStrings; } set { internStrings = value; } } + + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + /// The number of bytes to read, or -1 to read until the end of the stream + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context, int length) + { + Init(this, source, model, context, length); + } + + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + /// The number of bytes to read, or -1 to read until the end of the stream + [Obsolete("Please use ProtoReader.Create; this API may be removed in a future version", error: false)] + public ProtoReader(Stream source, TypeModel model, SerializationContext context, long length) + { + Init(this, source, model, context, length); + } + + private static void Init(ProtoReader reader, Stream source, TypeModel model, SerializationContext context, long length) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (!source.CanRead) throw new ArgumentException("Cannot read from stream", nameof(source)); + reader.source = source; + reader.ioBuffer = BufferPool.GetBuffer(); + reader.model = model; + bool isFixedLength = length >= 0; + reader.isFixedLength = isFixedLength; + reader.dataRemaining64 = isFixedLength ? length : 0; + + if (context == null) { context = SerializationContext.Default; } + else { context.Freeze(); } + reader.context = context; + reader.position64 = 0; + reader.available = reader.depth = reader.fieldNumber = reader.ioIndex = 0; + reader.blockEnd64 = long.MaxValue; + reader.internStrings = RuntimeTypeModel.Default.InternStrings; + reader.wireType = WireType.None; + reader.trapCount = 1; + if (reader.netCache == null) reader.netCache = new NetObjectCache(); + } + + private SerializationContext context; + + /// + /// Addition information about this deserialization operation. + /// + public SerializationContext Context => context; + + /// + /// Releases resources used by the reader, but importantly does not Dispose the + /// underlying stream; in many typical use-cases the stream is used for different + /// processes, so it is assumed that the consumer will Dispose their stream separately. + /// + public void Dispose() + { + // importantly, this does **not** own the stream, and does not dispose it + source = null; + model = null; + BufferPool.ReleaseBufferToPool(ref ioBuffer); + if (stringInterner != null) + { + stringInterner.Clear(); + stringInterner = null; + } + if (netCache != null) netCache.Clear(); + } + internal int TryReadUInt32VariantWithoutMoving(bool trimNegative, out uint value) + { + if (available < 10) Ensure(10, false); + if (available == 0) + { + value = 0; + return 0; + } + int readPos = ioIndex; + value = ioBuffer[readPos++]; + if ((value & 0x80) == 0) return 1; + value &= 0x7F; + if (available == 1) throw EoF(this); + + uint chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 7; + if ((chunk & 0x80) == 0) return 2; + if (available == 2) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 14; + if ((chunk & 0x80) == 0) return 3; + if (available == 3) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 21; + if ((chunk & 0x80) == 0) return 4; + if (available == 4) throw EoF(this); + + chunk = ioBuffer[readPos]; + value |= chunk << 28; // can only use 4 bits from this chunk + if ((chunk & 0xF0) == 0) return 5; + + if (trimNegative // allow for -ve values + && (chunk & 0xF0) == 0xF0 + && available >= 10 + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0xFF + && ioBuffer[++readPos] == 0x01) + { + return 10; + } + throw AddErrorData(new OverflowException(), this); + } + + private uint ReadUInt32Variant(bool trimNegative) + { + int read = TryReadUInt32VariantWithoutMoving(trimNegative, out uint value); + if (read > 0) + { + ioIndex += read; + available -= read; + position64 += read; + return value; + } + throw EoF(this); + } + + private bool TryReadUInt32Variant(out uint value) + { + int read = TryReadUInt32VariantWithoutMoving(false, out value); + if (read > 0) + { + ioIndex += read; + available -= read; + position64 += read; + return true; + } + return false; + } + + /// + /// Reads an unsigned 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public uint ReadUInt32() + { + switch (wireType) + { + case WireType.Variant: + return ReadUInt32Variant(false); + case WireType.Fixed32: + if (available < 4) Ensure(4, true); + position64 += 4; + available -= 4; + return ((uint)ioBuffer[ioIndex++]) + | (((uint)ioBuffer[ioIndex++]) << 8) + | (((uint)ioBuffer[ioIndex++]) << 16) + | (((uint)ioBuffer[ioIndex++]) << 24); + case WireType.Fixed64: + ulong val = ReadUInt64(); + checked { return (uint)val; } + default: + throw CreateWireTypeException(); + } + } + + /// + /// Returns the position of the current reader (note that this is not necessarily the same as the position + /// in the underlying stream, if multiple readers are used on the same stream) + /// + public int Position { get { return checked((int)position64); } } + + /// + /// Returns the position of the current reader (note that this is not necessarily the same as the position + /// in the underlying stream, if multiple readers are used on the same stream) + /// + public long LongPosition { get { return position64; } } + internal void Ensure(int count, bool strict) + { + Helpers.DebugAssert(available <= count, "Asking for data without checking first"); + if (count > ioBuffer.Length) + { + BufferPool.ResizeAndFlushLeft(ref ioBuffer, count, ioIndex, available); + ioIndex = 0; + } + else if (ioIndex + count >= ioBuffer.Length) + { + // need to shift the buffer data to the left to make space + Buffer.BlockCopy(ioBuffer, ioIndex, ioBuffer, 0, available); + ioIndex = 0; + } + count -= available; + int writePos = ioIndex + available, bytesRead; + int canRead = ioBuffer.Length - writePos; + if (isFixedLength) + { // throttle it if needed + if (dataRemaining64 < canRead) canRead = (int)dataRemaining64; + } + while (count > 0 && canRead > 0 && (bytesRead = source.Read(ioBuffer, writePos, canRead)) > 0) + { + available += bytesRead; + count -= bytesRead; + canRead -= bytesRead; + writePos += bytesRead; + if (isFixedLength) { dataRemaining64 -= bytesRead; } + } + if (strict && count > 0) + { + throw EoF(this); + } + + } + /// + /// Reads a signed 16-bit integer from the stream: Variant, Fixed32, Fixed64, SignedVariant + /// + public short ReadInt16() + { + checked { return (short)ReadInt32(); } + } + /// + /// Reads an unsigned 16-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public ushort ReadUInt16() + { + checked { return (ushort)ReadUInt32(); } + } + + /// + /// Reads an unsigned 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public byte ReadByte() + { + checked { return (byte)ReadUInt32(); } + } + + /// + /// Reads a signed 8-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public sbyte ReadSByte() + { + checked { return (sbyte)ReadInt32(); } + } + + /// + /// Reads a signed 32-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public int ReadInt32() + { + switch (wireType) + { + case WireType.Variant: + return (int)ReadUInt32Variant(true); + case WireType.Fixed32: + if (available < 4) Ensure(4, true); + position64 += 4; + available -= 4; + return ((int)ioBuffer[ioIndex++]) + | (((int)ioBuffer[ioIndex++]) << 8) + | (((int)ioBuffer[ioIndex++]) << 16) + | (((int)ioBuffer[ioIndex++]) << 24); + case WireType.Fixed64: + long l = ReadInt64(); + checked { return (int)l; } + case WireType.SignedVariant: + return Zag(ReadUInt32Variant(true)); + default: + throw CreateWireTypeException(); + } + } + private const long Int64Msb = ((long)1) << 63; + private const int Int32Msb = ((int)1) << 31; + private static int Zag(uint ziggedValue) + { + int value = (int)ziggedValue; + return (-(value & 0x01)) ^ ((value >> 1) & ~ProtoReader.Int32Msb); + } + + private static long Zag(ulong ziggedValue) + { + long value = (long)ziggedValue; + return (-(value & 0x01L)) ^ ((value >> 1) & ~ProtoReader.Int64Msb); + } + /// + /// Reads a signed 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public long ReadInt64() + { + switch (wireType) + { + case WireType.Variant: + return (long)ReadUInt64Variant(); + case WireType.Fixed32: + return ReadInt32(); + case WireType.Fixed64: + if (available < 8) Ensure(8, true); + position64 += 8; + available -= 8; + +#if NETCOREAPP2_1 + var result = System.Buffers.Binary.BinaryPrimitives.ReadInt64LittleEndian(ioBuffer.AsSpan(ioIndex, 8)); + + ioIndex+= 8; + + return result; +#else + return ((long)ioBuffer[ioIndex++]) + | (((long)ioBuffer[ioIndex++]) << 8) + | (((long)ioBuffer[ioIndex++]) << 16) + | (((long)ioBuffer[ioIndex++]) << 24) + | (((long)ioBuffer[ioIndex++]) << 32) + | (((long)ioBuffer[ioIndex++]) << 40) + | (((long)ioBuffer[ioIndex++]) << 48) + | (((long)ioBuffer[ioIndex++]) << 56); +#endif + case WireType.SignedVariant: + return Zag(ReadUInt64Variant()); + default: + throw CreateWireTypeException(); + } + } + + private int TryReadUInt64VariantWithoutMoving(out ulong value) + { + if (available < 10) Ensure(10, false); + if (available == 0) + { + value = 0; + return 0; + } + int readPos = ioIndex; + value = ioBuffer[readPos++]; + if ((value & 0x80) == 0) return 1; + value &= 0x7F; + if (available == 1) throw EoF(this); + + ulong chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 7; + if ((chunk & 0x80) == 0) return 2; + if (available == 2) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 14; + if ((chunk & 0x80) == 0) return 3; + if (available == 3) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 21; + if ((chunk & 0x80) == 0) return 4; + if (available == 4) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 28; + if ((chunk & 0x80) == 0) return 5; + if (available == 5) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 35; + if ((chunk & 0x80) == 0) return 6; + if (available == 6) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 42; + if ((chunk & 0x80) == 0) return 7; + if (available == 7) throw EoF(this); + + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 49; + if ((chunk & 0x80) == 0) return 8; + if (available == 8) throw EoF(this); + + chunk = ioBuffer[readPos++]; + value |= (chunk & 0x7F) << 56; + if ((chunk & 0x80) == 0) return 9; + if (available == 9) throw EoF(this); + + chunk = ioBuffer[readPos]; + value |= chunk << 63; // can only use 1 bit from this chunk + + if ((chunk & ~(ulong)0x01) != 0) throw AddErrorData(new OverflowException(), this); + return 10; + } + + private ulong ReadUInt64Variant() + { + int read = TryReadUInt64VariantWithoutMoving(out ulong value); + if (read > 0) + { + ioIndex += read; + available -= read; + position64 += read; + return value; + } + throw EoF(this); + } + + private Dictionary stringInterner; + private string Intern(string value) + { + if (value == null) return null; + if (value.Length == 0) return ""; + if (stringInterner == null) + { + stringInterner = new Dictionary + { + { value, value } + }; + } + else if (stringInterner.TryGetValue(value, out string found)) + { + value = found; + } + else + { + stringInterner.Add(value, value); + } + return value; + } + +#if COREFX + static readonly Encoding encoding = Encoding.UTF8; +#else + static readonly UTF8Encoding encoding = new UTF8Encoding(); +#endif + /// + /// Reads a string from the stream (using UTF8); supported wire-types: String + /// + public string ReadString() + { + if (wireType == WireType.String) + { + int bytes = (int)ReadUInt32Variant(false); + if (bytes == 0) return ""; + if (bytes < 0) ThrowInvalidLength(bytes); + if (available < bytes) Ensure(bytes, true); + + string s = encoding.GetString(ioBuffer, ioIndex, bytes); + + if (internStrings) { s = Intern(s); } + available -= bytes; + position64 += bytes; + ioIndex += bytes; + return s; + } + throw CreateWireTypeException(); + } + /// + /// Throws an exception indication that the given value cannot be mapped to an enum. + /// + public void ThrowEnumException(Type type, int value) + { + string desc = type == null ? "" : type.FullName; + throw AddErrorData(new ProtoException("No " + desc + " enum is mapped to the wire-value " + value.ToString()), this); + } + + private void ThrowInvalidLength(long length) + { + throw AddErrorData(new InvalidOperationException("Invalid length: " + length.ToString()), this); + } + + private Exception CreateWireTypeException() + { + return CreateException("Invalid wire-type; this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354"); + } + + private Exception CreateException(string message) + { + return AddErrorData(new ProtoException(message), this); + } + /// + /// Reads a double-precision number from the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + double ReadDouble() + { + switch (wireType) + { + case WireType.Fixed32: + return ReadSingle(); + case WireType.Fixed64: + long value = ReadInt64(); +#if FEAT_SAFE + return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); +#else + return *(double*)&value; +#endif + default: + throw CreateWireTypeException(); + } + } + + /// + /// Reads (merges) a sub-message from the stream, internally calling StartSubItem and EndSubItem, and (in between) + /// parsing the message in accordance with the model associated with the reader + /// + public static object ReadObject(object value, int key, ProtoReader reader) + { + return ReadTypedObject(value, key, reader, null); + } + + internal static object ReadTypedObject(object value, int key, ProtoReader reader, Type type) + { + if (reader.model == null) + { + throw AddErrorData(new InvalidOperationException("Cannot deserialize sub-objects unless a model is provided"), reader); + } + SubItemToken token = ProtoReader.StartSubItem(reader); + if (key >= 0) + { + value = reader.model.Deserialize(key, value, reader); + } + else if (type != null && reader.model.TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false, true, false, null)) + { + // ok + } + else + { + TypeModel.ThrowUnexpectedType(type); + } + ProtoReader.EndSubItem(token, reader); + return value; + } + + /// + /// Makes the end of consuming a nested message in the stream; the stream must be either at the correct EndGroup + /// marker, or all fields of the sub-message must have been consumed (in either case, this means ReadFieldHeader + /// should return zero) + /// + public static void EndSubItem(SubItemToken token, ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException("reader"); + long value64 = token.value64; + switch (reader.wireType) + { + case WireType.EndGroup: + if (value64 >= 0) throw AddErrorData(new ArgumentException("token"), reader); + if (-(int)value64 != reader.fieldNumber) throw reader.CreateException("Wrong group was ended"); // wrong group ended! + reader.wireType = WireType.None; // this releases ReadFieldHeader + reader.depth--; + break; + // case WireType.None: // TODO reinstate once reads reset the wire-type + default: + if (value64 < reader.position64) throw reader.CreateException($"Sub-message not read entirely; expected {value64}, was {reader.position64}"); + if (reader.blockEnd64 != reader.position64 && reader.blockEnd64 != long.MaxValue) + { + throw reader.CreateException("Sub-message not read correctly"); + } + reader.blockEnd64 = value64; + reader.depth--; + break; + /*default: + throw reader.BorkedIt(); */ + } + } + + /// + /// Begins consuming a nested message in the stream; supported wire-types: StartGroup, String + /// + /// The token returned must be help and used when callining EndSubItem + public static SubItemToken StartSubItem(ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException("reader"); + switch (reader.wireType) + { + case WireType.StartGroup: + reader.wireType = WireType.None; // to prevent glitches from double-calling + reader.depth++; + return new SubItemToken((long)(-reader.fieldNumber)); + case WireType.String: + long len = (long)reader.ReadUInt64Variant(); + if (len < 0) reader.ThrowInvalidLength(len); + long lastEnd = reader.blockEnd64; + reader.blockEnd64 = reader.position64 + len; + reader.depth++; + return new SubItemToken(lastEnd); + default: + throw reader.CreateWireTypeException(); // throws + } + } + + /// + /// Reads a field header from the stream, setting the wire-type and retuning the field number. If no + /// more fields are available, then 0 is returned. This methods respects sub-messages. + /// + public int ReadFieldHeader() + { + // at the end of a group the caller must call EndSubItem to release the + // reader (which moves the status to Error, since ReadFieldHeader must + // then be called) + if (blockEnd64 <= position64 || wireType == WireType.EndGroup) { return 0; } + + if (TryReadUInt32Variant(out uint tag) && tag != 0) + { + wireType = (WireType)(tag & 7); + fieldNumber = (int)(tag >> 3); + if (fieldNumber < 1) throw new ProtoException("Invalid field in source data: " + fieldNumber.ToString()); + } + else + { + wireType = WireType.None; + fieldNumber = 0; + } + if (wireType == ProtoBuf.WireType.EndGroup) + { + if (depth > 0) return 0; // spoof an end, but note we still set the field-number + throw new ProtoException("Unexpected end-group in source data; this usually means the source data is corrupt"); + } + return fieldNumber; + } + /// + /// Looks ahead to see whether the next field in the stream is what we expect + /// (typically; what we've just finished reading - for example ot read successive list items) + /// + public bool TryReadFieldHeader(int field) + { + // check for virtual end of stream + if (blockEnd64 <= position64 || wireType == WireType.EndGroup) { return false; } + + int read = TryReadUInt32VariantWithoutMoving(false, out uint tag); + WireType tmpWireType; // need to catch this to exclude (early) any "end group" tokens + if (read > 0 && ((int)tag >> 3) == field + && (tmpWireType = (WireType)(tag & 7)) != WireType.EndGroup) + { + wireType = tmpWireType; + fieldNumber = field; + position64 += read; + ioIndex += read; + available -= read; + return true; + } + return false; + } + + /// + /// Get the TypeModel associated with this reader + /// + public TypeModel Model { get { return model; } } + + /// + /// Compares the streams current wire-type to the hinted wire-type, updating the reader if necessary; for example, + /// a Variant may be updated to SignedVariant. If the hinted wire-type is unrelated then no change is made. + /// + public void Hint(WireType wireType) + { + if (this.wireType == wireType) { } // fine; everything as we expect + else if (((int)wireType & 7) == (int)this.wireType) + { // the underling type is a match; we're customising it with an extension + this.wireType = wireType; + } + // note no error here; we're OK about using alternative data + } + + /// + /// Verifies that the stream's current wire-type is as expected, or a specialized sub-type (for example, + /// SignedVariant) - in which case the current wire-type is updated. Otherwise an exception is thrown. + /// + public void Assert(WireType wireType) + { + if (this.wireType == wireType) { } // fine; everything as we expect + else if (((int)wireType & 7) == (int)this.wireType) + { // the underling type is a match; we're customising it with an extension + this.wireType = wireType; + } + else + { // nope; that is *not* what we were expecting! + throw CreateWireTypeException(); + } + } + + /// + /// Discards the data for the current field. + /// + public void SkipField() + { + switch (wireType) + { + case WireType.Fixed32: + if (available < 4) Ensure(4, true); + available -= 4; + ioIndex += 4; + position64 += 4; + return; + case WireType.Fixed64: + if (available < 8) Ensure(8, true); + available -= 8; + ioIndex += 8; + position64 += 8; + return; + case WireType.String: + long len = (long)ReadUInt64Variant(); + if (len < 0) ThrowInvalidLength(len); + if (len <= available) + { // just jump it! + available -= (int)len; + ioIndex += (int)len; + position64 += len; + return; + } + // everything remaining in the buffer is garbage + position64 += len; // assumes success, but if it fails we're screwed anyway + len -= available; // discount anything we've got to-hand + ioIndex = available = 0; // note that we have no data in the buffer + if (isFixedLength) + { + if (len > dataRemaining64) throw EoF(this); + // else assume we're going to be OK + dataRemaining64 -= len; + } + ProtoReader.Seek(source, len, ioBuffer); + return; + case WireType.Variant: + case WireType.SignedVariant: + ReadUInt64Variant(); // and drop it + return; + case WireType.StartGroup: + int originalFieldNumber = this.fieldNumber; + depth++; // need to satisfy the sanity-checks in ReadFieldHeader + while (ReadFieldHeader() > 0) { SkipField(); } + depth--; + if (wireType == WireType.EndGroup && fieldNumber == originalFieldNumber) + { // we expect to exit in a similar state to how we entered + wireType = ProtoBuf.WireType.None; + return; + } + throw CreateWireTypeException(); + case WireType.None: // treat as explicit errorr + case WireType.EndGroup: // treat as explicit error + default: // treat as implicit error + throw CreateWireTypeException(); + } + } + + /// + /// Reads an unsigned 64-bit integer from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public ulong ReadUInt64() + { + switch (wireType) + { + case WireType.Variant: + return ReadUInt64Variant(); + case WireType.Fixed32: + return ReadUInt32(); + case WireType.Fixed64: + if (available < 8) Ensure(8, true); + position64 += 8; + available -= 8; + + return ((ulong)ioBuffer[ioIndex++]) + | (((ulong)ioBuffer[ioIndex++]) << 8) + | (((ulong)ioBuffer[ioIndex++]) << 16) + | (((ulong)ioBuffer[ioIndex++]) << 24) + | (((ulong)ioBuffer[ioIndex++]) << 32) + | (((ulong)ioBuffer[ioIndex++]) << 40) + | (((ulong)ioBuffer[ioIndex++]) << 48) + | (((ulong)ioBuffer[ioIndex++]) << 56); + default: + throw CreateWireTypeException(); + } + } + /// + /// Reads a single-precision number from the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + float ReadSingle() + { + switch (wireType) + { + case WireType.Fixed32: + { + int value = ReadInt32(); +#if FEAT_SAFE + return BitConverter.ToSingle(BitConverter.GetBytes(value), 0); +#else + return *(float*)&value; +#endif + } + case WireType.Fixed64: + { + double value = ReadDouble(); + float f = (float)value; + if (float.IsInfinity(f) && !double.IsInfinity(value)) + { + throw AddErrorData(new OverflowException(), this); + } + return f; + } + default: + throw CreateWireTypeException(); + } + } + + /// + /// Reads a boolean value from the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + /// + public bool ReadBoolean() + { + switch (ReadUInt32()) + { + case 0: return false; + case 1: return true; + default: throw CreateException("Unexpected boolean value"); + } + } + + private static readonly byte[] EmptyBlob = new byte[0]; + /// + /// Reads a byte-sequence from the stream, appending them to an existing byte-sequence (which can be null); supported wire-types: String + /// + public static byte[] AppendBytes(byte[] value, ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException(nameof(reader)); + switch (reader.wireType) + { + case WireType.String: + int len = (int)reader.ReadUInt32Variant(false); + reader.wireType = WireType.None; + if (len == 0) return value ?? EmptyBlob; + if (len < 0) reader.ThrowInvalidLength(len); + int offset; + if (value == null || value.Length == 0) + { + offset = 0; + value = new byte[len]; + } + else + { + offset = value.Length; + byte[] tmp = new byte[value.Length + len]; + Buffer.BlockCopy(value, 0, tmp, 0, value.Length); + value = tmp; + } + // value is now sized with the final length, and (if necessary) + // contains the old data up to "offset" + reader.position64 += len; // assume success + while (len > reader.available) + { + if (reader.available > 0) + { + // copy what we *do* have + Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, reader.available); + len -= reader.available; + offset += reader.available; + reader.ioIndex = reader.available = 0; // we've drained the buffer + } + // now refill the buffer (without overflowing it) + int count = len > reader.ioBuffer.Length ? reader.ioBuffer.Length : len; + if (count > 0) reader.Ensure(count, true); + } + // at this point, we know that len <= available + if (len > 0) + { // still need data, but we have enough buffered + Buffer.BlockCopy(reader.ioBuffer, reader.ioIndex, value, offset, len); + reader.ioIndex += len; + reader.available -= len; + } + return value; + case WireType.Variant: + return new byte[0]; + default: + throw reader.CreateWireTypeException(); + } + } + + //static byte[] ReadBytes(Stream stream, int length) + //{ + // if (stream == null) throw new ArgumentNullException("stream"); + // if (length < 0) throw new ArgumentOutOfRangeException("length"); + // byte[] buffer = new byte[length]; + // int offset = 0, read; + // while (length > 0 && (read = stream.Read(buffer, offset, length)) > 0) + // { + // length -= read; + // } + // if (length > 0) throw EoF(null); + // return buffer; + //} + private static int ReadByteOrThrow(Stream source) + { + int val = source.ReadByte(); + if (val < 0) throw EoF(null); + return val; + } + + /// + /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length + /// reader to be created. + /// + public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber) + => ReadLengthPrefix(source, expectHeader, style, out fieldNumber, out int bytesRead); + + /// + /// Reads a little-endian encoded integer. An exception is thrown if the data is not all available. + /// + public static int DirectReadLittleEndianInt32(Stream source) + { + return ReadByteOrThrow(source) + | (ReadByteOrThrow(source) << 8) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 24); + } + + /// + /// Reads a big-endian encoded integer. An exception is thrown if the data is not all available. + /// + public static int DirectReadBigEndianInt32(Stream source) + { + return (ReadByteOrThrow(source) << 24) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 8) + | ReadByteOrThrow(source); + } + + /// + /// Reads a varint encoded integer. An exception is thrown if the data is not all available. + /// + public static int DirectReadVarintInt32(Stream source) + { + int bytes = TryReadUInt64Variant(source, out ulong val); + if (bytes <= 0) throw EoF(null); + return checked((int)val); + } + + /// + /// Reads a string (of a given lenth, in bytes) directly from the source into a pre-existing buffer. An exception is thrown if the data is not all available. + /// + public static void DirectReadBytes(Stream source, byte[] buffer, int offset, int count) + { + int read; + if (source == null) throw new ArgumentNullException("source"); + while (count > 0 && (read = source.Read(buffer, offset, count)) > 0) + { + count -= read; + offset += read; + } + if (count > 0) throw EoF(null); + } + + /// + /// Reads a given number of bytes directly from the source. An exception is thrown if the data is not all available. + /// + public static byte[] DirectReadBytes(Stream source, int count) + { + byte[] buffer = new byte[count]; + DirectReadBytes(source, buffer, 0, count); + return buffer; + } + + /// + /// Reads a string (of a given lenth, in bytes) directly from the source. An exception is thrown if the data is not all available. + /// + public static string DirectReadString(Stream source, int length) + { + byte[] buffer = new byte[length]; + DirectReadBytes(source, buffer, 0, length); + return Encoding.UTF8.GetString(buffer, 0, length); + } + + /// + /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length + /// reader to be created. + /// + public static int ReadLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead) + { + if (style == PrefixStyle.None) + { + bytesRead = fieldNumber = 0; + return int.MaxValue; // avoid the long.maxvalue causing overflow + } + long len64 = ReadLongLengthPrefix(source, expectHeader, style, out fieldNumber, out bytesRead); + return checked((int)len64); + } + + /// + /// Reads the length-prefix of a message from a stream without buffering additional data, allowing a fixed-length + /// reader to be created. + /// + public static long ReadLongLengthPrefix(Stream source, bool expectHeader, PrefixStyle style, out int fieldNumber, out int bytesRead) + { + fieldNumber = 0; + switch (style) + { + case PrefixStyle.None: + bytesRead = 0; + return long.MaxValue; + case PrefixStyle.Base128: + ulong val; + int tmpBytesRead; + bytesRead = 0; + if (expectHeader) + { + tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val); + bytesRead += tmpBytesRead; + if (tmpBytesRead > 0) + { + if ((val & 7) != (uint)WireType.String) + { // got a header, but it isn't a string + throw new InvalidOperationException(); + } + fieldNumber = (int)(val >> 3); + tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val); + bytesRead += tmpBytesRead; + if (bytesRead == 0) + { // got a header, but no length + throw EoF(null); + } + return (long)val; + } + else + { // no header + bytesRead = 0; + return -1; + } + } + // check for a length + tmpBytesRead = ProtoReader.TryReadUInt64Variant(source, out val); + bytesRead += tmpBytesRead; + return bytesRead < 0 ? -1 : (long)val; + + case PrefixStyle.Fixed32: + { + int b = source.ReadByte(); + if (b < 0) + { + bytesRead = 0; + return -1; + } + bytesRead = 4; + return b + | (ReadByteOrThrow(source) << 8) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 24); + } + case PrefixStyle.Fixed32BigEndian: + { + int b = source.ReadByte(); + if (b < 0) + { + bytesRead = 0; + return -1; + } + bytesRead = 4; + return (b << 24) + | (ReadByteOrThrow(source) << 16) + | (ReadByteOrThrow(source) << 8) + | ReadByteOrThrow(source); + } + default: + throw new ArgumentOutOfRangeException("style"); + } + } + + /// The number of bytes consumed; 0 if no data available + private static int TryReadUInt64Variant(Stream source, out ulong value) + { + value = 0; + int b = source.ReadByte(); + if (b < 0) { return 0; } + value = (uint)b; + if ((value & 0x80) == 0) { return 1; } + value &= 0x7F; + int bytesRead = 1, shift = 7; + while (bytesRead < 9) + { + b = source.ReadByte(); + if (b < 0) throw EoF(null); + value |= ((ulong)b & 0x7F) << shift; + shift += 7; + bytesRead++; + + if ((b & 0x80) == 0) return bytesRead; + } + b = source.ReadByte(); + if (b < 0) throw EoF(null); + if ((b & 1) == 0) // only use 1 bit from the last byte + { + value |= ((ulong)b & 0x7F) << shift; + return ++bytesRead; + } + throw new OverflowException(); + } + + internal static void Seek(Stream source, long count, byte[] buffer) + { + if (source.CanSeek) + { + source.Seek(count, SeekOrigin.Current); + count = 0; + } + else if (buffer != null) + { + int bytesRead; + while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + { + count -= bytesRead; + } + while (count > 0 && (bytesRead = source.Read(buffer, 0, (int)count)) > 0) + { + count -= bytesRead; + } + } + else // borrow a buffer + { + buffer = BufferPool.GetBuffer(); + try + { + int bytesRead; + while (count > buffer.Length && (bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + { + count -= bytesRead; + } + while (count > 0 && (bytesRead = source.Read(buffer, 0, (int)count)) > 0) + { + count -= bytesRead; + } + } + finally + { + BufferPool.ReleaseBufferToPool(ref buffer); + } + } + if (count > 0) throw EoF(null); + } + internal static Exception AddErrorData(Exception exception, ProtoReader source) + { +#if !CF && !PORTABLE + if (exception != null && source != null && !exception.Data.Contains("protoSource")) + { + exception.Data.Add("protoSource", string.Format("tag={0}; wire-type={1}; offset={2}; depth={3}", + source.fieldNumber, source.wireType, source.position64, source.depth)); + } +#endif + return exception; + } + + private static Exception EoF(ProtoReader source) + { + return AddErrorData(new EndOfStreamException(), source); + } + + /// + /// Copies the current field into the instance as extension data + /// + public void AppendExtensionData(IExtensible instance) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + IExtension extn = instance.GetExtensionObject(true); + bool commit = false; + // unusually we *don't* want "using" here; the "finally" does that, with + // the extension object being responsible for disposal etc + Stream dest = extn.BeginAppend(); + try + { + //TODO: replace this with stream-based, buffered raw copying + using (ProtoWriter writer = ProtoWriter.Create(dest, model, null)) + { + AppendExtensionField(writer); + writer.Close(); + } + commit = true; + } + finally { extn.EndAppend(dest, commit); } + } + + private void AppendExtensionField(ProtoWriter writer) + { + //TODO: replace this with stream-based, buffered raw copying + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, writer); + switch (wireType) + { + case WireType.Fixed32: + ProtoWriter.WriteInt32(ReadInt32(), writer); + return; + case WireType.Variant: + case WireType.SignedVariant: + case WireType.Fixed64: + ProtoWriter.WriteInt64(ReadInt64(), writer); + return; + case WireType.String: + ProtoWriter.WriteBytes(AppendBytes(null, this), writer); + return; + case WireType.StartGroup: + SubItemToken readerToken = StartSubItem(this), + writerToken = ProtoWriter.StartSubItem(null, writer); + while (ReadFieldHeader() > 0) { AppendExtensionField(writer); } + EndSubItem(readerToken, this); + ProtoWriter.EndSubItem(writerToken, writer); + return; + case WireType.None: // treat as explicit errorr + case WireType.EndGroup: // treat as explicit error + default: // treat as implicit error + throw CreateWireTypeException(); + } + } + + /// + /// Indicates whether the reader still has data remaining in the current sub-item, + /// additionally setting the wire-type for the next field if there is more data. + /// This is used when decoding packed data. + /// + public static bool HasSubValue(ProtoBuf.WireType wireType, ProtoReader source) + { + if (source == null) throw new ArgumentNullException("source"); + // check for virtual end of stream + if (source.blockEnd64 <= source.position64 || wireType == WireType.EndGroup) { return false; } + source.wireType = wireType; + return true; + } + + internal int GetTypeKey(ref Type type) + { + return model.GetKey(ref type); + } + + internal NetObjectCache NetCache => netCache; + + internal Type DeserializeType(string value) + { + return TypeModel.DeserializeType(model, value); + } + + internal void SetRootObject(object value) + { + netCache.SetKeyedObject(NetObjectCache.Root, value); + trapCount--; + } + + /// + /// Utility method, not intended for public use; this helps maintain the root object is complex scenarios + /// + public static void NoteObject(object value, ProtoReader reader) + { + if (reader == null) throw new ArgumentNullException("reader"); + if (reader.trapCount != 0) + { + reader.netCache.RegisterTrappedObject(value); + reader.trapCount--; + } + } + + /// + /// Reads a Type from the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String + /// + public Type ReadType() + { + return TypeModel.DeserializeType(model, ReadString()); + } + + internal void TrapNextObject(int newObjectKey) + { + trapCount++; + netCache.SetKeyedObject(newObjectKey, null); // use null as a temp + } + + internal void CheckFullyConsumed() + { + if (isFixedLength) + { + if (dataRemaining64 != 0) throw new ProtoException("Incorrect number of bytes consumed"); + } + else + { + if (available != 0) throw new ProtoException("Unconsumed data left in the buffer; this suggests corrupt input"); + } + } + + /// + /// Merge two objects using the details from the current reader; this is used to change the type + /// of objects when an inheritance relationship is discovered later than usual during deserilazation. + /// + public static object Merge(ProtoReader parent, object from, object to) + { + if (parent == null) throw new ArgumentNullException("parent"); + TypeModel model = parent.Model; + SerializationContext ctx = parent.Context; + if (model == null) throw new InvalidOperationException("Types cannot be merged unless a type-model has been specified"); + using (var ms = new MemoryStream()) + { + model.Serialize(ms, from, ctx); + ms.Position = 0; + return model.Deserialize(ms, to, null); + } + } + + #region RECYCLER + + internal static ProtoReader Create(Stream source, TypeModel model, SerializationContext context, int len) + => Create(source, model, context, (long)len); + /// + /// Creates a new reader against a stream + /// + /// The source stream + /// The model to use for serialization; this can be null, but this will impair the ability to deserialize sub-objects + /// Additional context about this serialization operation + /// The number of bytes to read, or -1 to read until the end of the stream + public static ProtoReader Create(Stream source, TypeModel model, SerializationContext context = null, long length = TO_EOF) + { + ProtoReader reader = GetRecycled(); + if (reader == null) + { +#pragma warning disable CS0618 + return new ProtoReader(source, model, context, length); +#pragma warning restore CS0618 + } + Init(reader, source, model, context, length); + return reader; + } + +#if !PLAT_NO_THREADSTATIC + [ThreadStatic] + private static ProtoReader lastReader; + + private static ProtoReader GetRecycled() + { + ProtoReader tmp = lastReader; + lastReader = null; + return tmp; + } + internal static void Recycle(ProtoReader reader) + { + if (reader != null) + { + reader.Dispose(); + lastReader = reader; + } + } +#elif !PLAT_NO_INTERLOCKED + private static object lastReader; + private static ProtoReader GetRecycled() + { + return (ProtoReader)System.Threading.Interlocked.Exchange(ref lastReader, null); + } + internal static void Recycle(ProtoReader reader) + { + if(reader != null) + { + reader.Dispose(); + System.Threading.Interlocked.Exchange(ref lastReader, reader); + } + } +#else + private static readonly object recycleLock = new object(); + private static ProtoReader lastReader; + private static ProtoReader GetRecycled() + { + lock(recycleLock) + { + ProtoReader tmp = lastReader; + lastReader = null; + return tmp; + } + } + internal static void Recycle(ProtoReader reader) + { + if(reader != null) + { + reader.Dispose(); + lock(recycleLock) + { + lastReader = reader; + } + } + } +#endif + + #endregion + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoReader.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoReader.cs.meta new file mode 100644 index 00000000..0826a162 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd9c8ee218e18b14b9058926b6bbc8fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoWriter.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoWriter.cs new file mode 100644 index 00000000..23fa42d5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoWriter.cs @@ -0,0 +1,1003 @@ +using System; +using System.IO; +using System.Text; +using ProtoBuf.Meta; + +namespace ProtoBuf +{ + /// + /// Represents an output stream for writing protobuf data. + /// + /// Why is the API backwards (static methods with writer arguments)? + /// See: http://marcgravell.blogspot.com/2010/03/last-will-be-first-and-first-will-be.html + /// + public sealed class ProtoWriter : IDisposable + { + private Stream dest; + TypeModel model; + /// + /// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type). + /// + /// The object to write. + /// The key that uniquely identifies the type within the model. + /// The destination. + public static void WriteObject(object value, int key, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + + SubItemToken token = StartSubItem(value, writer); + if (key >= 0) + { + writer.model.Serialize(key, value, writer); + } + else if (writer.model != null && writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null)) + { + // all ok + } + else + { + TypeModel.ThrowUnexpectedType(value.GetType()); + } + + EndSubItem(token, writer); + } + /// + /// Write an encapsulated sub-object, using the supplied unique key (reprasenting a type) - but the + /// caller is asserting that this relationship is non-recursive; no recursion check will be + /// performed. + /// + /// The object to write. + /// The key that uniquely identifies the type within the model. + /// The destination. + public static void WriteRecursionSafeObject(object value, int key, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + SubItemToken token = StartSubItem(null, writer); + writer.model.Serialize(key, value, writer); + EndSubItem(token, writer); + } + + internal static void WriteObject(object value, int key, ProtoWriter writer, PrefixStyle style, int fieldNumber) + { + if (writer.model == null) + { + throw new InvalidOperationException("Cannot serialize sub-objects unless a model is provided"); + } + if (writer.wireType != WireType.None) throw ProtoWriter.CreateException(writer); + + switch (style) + { + case PrefixStyle.Base128: + writer.wireType = WireType.String; + writer.fieldNumber = fieldNumber; + if (fieldNumber > 0) WriteHeaderCore(fieldNumber, WireType.String, writer); + break; + case PrefixStyle.Fixed32: + case PrefixStyle.Fixed32BigEndian: + writer.fieldNumber = 0; + writer.wireType = WireType.Fixed32; + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + SubItemToken token = StartSubItem(value, writer, true); + if (key < 0) + { + if (!writer.model.TrySerializeAuxiliaryType(writer, value.GetType(), DataFormat.Default, Serializer.ListItemTag, value, false, null)) + { + TypeModel.ThrowUnexpectedType(value.GetType()); + } + } + else + { + writer.model.Serialize(key, value, writer); + } + EndSubItem(token, writer, style); + } + + internal int GetTypeKey(ref Type type) + { + return model.GetKey(ref type); + } + + private readonly NetObjectCache netCache = new NetObjectCache(); + internal NetObjectCache NetCache => netCache; + + private int fieldNumber, flushLock; + WireType wireType; + internal WireType WireType { get { return wireType; } } + /// + /// Writes a field-header, indicating the format of the next data we plan to write. + /// + public static void WriteFieldHeader(int fieldNumber, WireType wireType, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.wireType != WireType.None) throw new InvalidOperationException("Cannot write a " + wireType.ToString() + + " header until the " + writer.wireType.ToString() + " data has been written"); + if (fieldNumber < 0) throw new ArgumentOutOfRangeException("fieldNumber"); +#if DEBUG + switch (wireType) + { // validate requested header-type + case WireType.Fixed32: + case WireType.Fixed64: + case WireType.String: + case WireType.StartGroup: + case WireType.SignedVariant: + case WireType.Variant: + break; // fine + case WireType.None: + case WireType.EndGroup: + default: + throw new ArgumentException("Invalid wire-type: " + wireType.ToString(), "wireType"); + } +#endif + if (writer.packedFieldNumber == 0) + { + writer.fieldNumber = fieldNumber; + writer.wireType = wireType; + WriteHeaderCore(fieldNumber, wireType, writer); + } + else if (writer.packedFieldNumber == fieldNumber) + { // we'll set things up, but note we *don't* actually write the header here + switch (wireType) + { + case WireType.Fixed32: + case WireType.Fixed64: + case WireType.Variant: + case WireType.SignedVariant: + break; // fine + default: + throw new InvalidOperationException("Wire-type cannot be encoded as packed: " + wireType.ToString()); + } + writer.fieldNumber = fieldNumber; + writer.wireType = wireType; + } + else + { + throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString()); + } + } + internal static void WriteHeaderCore(int fieldNumber, WireType wireType, ProtoWriter writer) + { + uint header = (((uint)fieldNumber) << 3) + | (((uint)wireType) & 7); + WriteUInt32Variant(header, writer); + } + + /// + /// Writes a byte-array to the stream; supported wire-types: String + /// + public static void WriteBytes(byte[] data, ProtoWriter writer) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + ProtoWriter.WriteBytes(data, 0, data.Length, writer); + } + /// + /// Writes a byte-array to the stream; supported wire-types: String + /// + public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed32: + if (length != 4) throw new ArgumentException(nameof(length)); + goto CopyFixedLength; // ugly but effective + case WireType.Fixed64: + if (length != 8) throw new ArgumentException(nameof(length)); + goto CopyFixedLength; // ugly but effective + case WireType.String: + WriteUInt32Variant((uint)length, writer); + writer.wireType = WireType.None; + if (length == 0) return; + if (writer.flushLock != 0 || length <= writer.ioBuffer.Length) // write to the buffer + { + goto CopyFixedLength; // ugly but effective + } + // writing data that is bigger than the buffer (and the buffer + // isn't currently locked due to a sub-object needing the size backfilled) + Flush(writer); // commit any existing data from the buffer + // now just write directly to the underlying stream + writer.dest.Write(data, offset, length); + writer.position64 += length; // since we've flushed offset etc is 0, and remains + // zero since we're writing directly to the stream + return; + } + throw CreateException(writer); + CopyFixedLength: // no point duplicating this lots of times, and don't really want another stackframe + DemandSpace(length, writer); + Buffer.BlockCopy(data, offset, writer.ioBuffer, writer.ioIndex, length); + IncrementedAndReset(length, writer); + } + private static void CopyRawFromStream(Stream source, ProtoWriter writer) + { + byte[] buffer = writer.ioBuffer; + int space = buffer.Length - writer.ioIndex, bytesRead = 1; // 1 here to spoof case where already full + + // try filling the buffer first + while (space > 0 && (bytesRead = source.Read(buffer, writer.ioIndex, space)) > 0) + { + writer.ioIndex += bytesRead; + writer.position64 += bytesRead; + space -= bytesRead; + } + if (bytesRead <= 0) return; // all done using just the buffer; stream exhausted + + // at this point the stream still has data, but buffer is full; + if (writer.flushLock == 0) + { + // flush the buffer and write to the underlying stream instead + Flush(writer); + while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + { + writer.dest.Write(buffer, 0, bytesRead); + writer.position64 += bytesRead; + } + } + else + { + do + { + // need more space; resize (double) as necessary, + // requesting a reasonable minimum chunk each time + // (128 is the minimum; there may actually be much + // more space than this in the buffer) + DemandSpace(128, writer); + if ((bytesRead = source.Read(writer.ioBuffer, writer.ioIndex, + writer.ioBuffer.Length - writer.ioIndex)) <= 0) break; + writer.position64 += bytesRead; + writer.ioIndex += bytesRead; + } while (true); + } + + } + private static void IncrementedAndReset(int length, ProtoWriter writer) + { + Helpers.DebugAssert(length >= 0); + writer.ioIndex += length; + writer.position64 += length; + writer.wireType = WireType.None; + } + int depth = 0; + const int RecursionCheckDepth = 25; + /// + /// Indicates the start of a nested record. + /// + /// The instance to write. + /// The destination. + /// A token representing the state of the stream; this token is given to EndSubItem. + public static SubItemToken StartSubItem(object instance, ProtoWriter writer) + { + return StartSubItem(instance, writer, false); + } + + MutableList recursionStack; + private void CheckRecursionStackAndPush(object instance) + { + int hitLevel; + if (recursionStack == null) { recursionStack = new MutableList(); } + else if (instance != null && (hitLevel = recursionStack.IndexOfReference(instance)) >= 0) + { +#if DEBUG + Helpers.DebugWriteLine("Stack:"); + foreach (object obj in recursionStack) + { + Helpers.DebugWriteLine(obj == null ? "" : obj.ToString()); + } + Helpers.DebugWriteLine(instance == null ? "" : instance.ToString()); +#endif + throw new ProtoException("Possible recursion detected (offset: " + (recursionStack.Count - hitLevel).ToString() + " level(s)): " + instance.ToString()); + } + recursionStack.Add(instance); + } + private void PopRecursionStack() { recursionStack.RemoveLast(); } + + private static SubItemToken StartSubItem(object instance, ProtoWriter writer, bool allowFixed) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (++writer.depth > RecursionCheckDepth) + { + writer.CheckRecursionStackAndPush(instance); + } + if (writer.packedFieldNumber != 0) throw new InvalidOperationException("Cannot begin a sub-item while performing packed encoding"); + switch (writer.wireType) + { + case WireType.StartGroup: + writer.wireType = WireType.None; + return new SubItemToken((long)(-writer.fieldNumber)); + case WireType.String: +#if DEBUG + if (writer.model != null && writer.model.ForwardsOnly) + { + throw new ProtoException("Should not be buffering data: " + instance ?? "(null)"); + } +#endif + writer.wireType = WireType.None; + DemandSpace(32, writer); // make some space in anticipation... + writer.flushLock++; + writer.position64++; + return new SubItemToken((long)(writer.ioIndex++)); // leave 1 space (optimistic) for length + case WireType.Fixed32: + { + if (!allowFixed) throw CreateException(writer); + DemandSpace(32, writer); // make some space in anticipation... + writer.flushLock++; + SubItemToken token = new SubItemToken((long)writer.ioIndex); + ProtoWriter.IncrementedAndReset(4, writer); // leave 4 space (rigid) for length + return token; + } + default: + throw CreateException(writer); + } + } + + /// + /// Indicates the end of a nested record. + /// + /// The token obtained from StartubItem. + /// The destination. + public static void EndSubItem(SubItemToken token, ProtoWriter writer) + { + EndSubItem(token, writer, PrefixStyle.Base128); + } + private static void EndSubItem(SubItemToken token, ProtoWriter writer, PrefixStyle style) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.wireType != WireType.None) { throw CreateException(writer); } + int value = (int)token.value64; + if (writer.depth <= 0) throw CreateException(writer); + if (writer.depth-- > RecursionCheckDepth) + { + writer.PopRecursionStack(); + } + writer.packedFieldNumber = 0; // ending the sub-item always wipes packed encoding + if (value < 0) + { // group - very simple append + WriteHeaderCore(-value, WireType.EndGroup, writer); + writer.wireType = WireType.None; + return; + } + + // so we're backfilling the length into an existing sequence + int len; + switch (style) + { + case PrefixStyle.Fixed32: + len = (int)((writer.ioIndex - value) - 4); + ProtoWriter.WriteInt32ToBuffer(len, writer.ioBuffer, value); + break; + case PrefixStyle.Fixed32BigEndian: + len = (int)((writer.ioIndex - value) - 4); + byte[] buffer = writer.ioBuffer; + ProtoWriter.WriteInt32ToBuffer(len, buffer, value); + // and swap the byte order + byte b = buffer[value]; + buffer[value] = buffer[value + 3]; + buffer[value + 3] = b; + b = buffer[value + 1]; + buffer[value + 1] = buffer[value + 2]; + buffer[value + 2] = b; + break; + case PrefixStyle.Base128: + // string - complicated because we only reserved one byte; + // if the prefix turns out to need more than this then + // we need to shuffle the existing data + len = (int)((writer.ioIndex - value) - 1); + int offset = 0; + uint tmp = (uint)len; + while ((tmp >>= 7) != 0) offset++; + if (offset == 0) + { + writer.ioBuffer[value] = (byte)(len & 0x7F); + } + else + { + DemandSpace(offset, writer); + byte[] blob = writer.ioBuffer; + Buffer.BlockCopy(blob, value + 1, blob, value + 1 + offset, len); + tmp = (uint)len; + do + { + blob[value++] = (byte)((tmp & 0x7F) | 0x80); + } while ((tmp >>= 7) != 0); + blob[value - 1] = (byte)(blob[value - 1] & ~0x80); + writer.position64 += offset; + writer.ioIndex += offset; + } + break; + default: + throw new ArgumentOutOfRangeException("style"); + } + // and this object is no longer a blockage - also flush if sensible + const int ADVISORY_FLUSH_SIZE = 1024; + if (--writer.flushLock == 0 && writer.ioIndex >= ADVISORY_FLUSH_SIZE) + { + ProtoWriter.Flush(writer); + } + + } + + /// + /// Creates a new writer against a stream + /// + /// The destination stream + /// The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects + /// Additional context about this serialization operation + public static ProtoWriter Create(Stream dest, TypeModel model, SerializationContext context = null) +#pragma warning disable CS0618 + => new ProtoWriter(dest, model, context); +#pragma warning restore CS0618 + + /// + /// Creates a new writer against a stream + /// + /// The destination stream + /// The model to use for serialization; this can be null, but this will impair the ability to serialize sub-objects + /// Additional context about this serialization operation + [Obsolete("Please use ProtoWriter.Create; this API may be removed in a future version", error: false)] + public ProtoWriter(Stream dest, TypeModel model, SerializationContext context) + { + if (dest == null) throw new ArgumentNullException("dest"); + if (!dest.CanWrite) throw new ArgumentException("Cannot write to stream", "dest"); + //if (model == null) throw new ArgumentNullException("model"); + this.dest = dest; + this.ioBuffer = BufferPool.GetBuffer(); + this.model = model; + this.wireType = WireType.None; + if (context == null) { context = SerializationContext.Default; } + else { context.Freeze(); } + this.context = context; + + } + + private readonly SerializationContext context; + /// + /// Addition information about this serialization operation. + /// + public SerializationContext Context => context; + + void IDisposable.Dispose() + { + Dispose(); + } + + private void Dispose() + { // importantly, this does **not** own the stream, and does not dispose it + if (dest != null) + { + Flush(this); + dest = null; + } + model = null; + BufferPool.ReleaseBufferToPool(ref ioBuffer); + } + + private byte[] ioBuffer; + private int ioIndex; + // note that this is used by some of the unit tests and should not be removed + internal static long GetLongPosition(ProtoWriter writer) { return writer.position64; } + internal static int GetPosition(ProtoWriter writer) { return checked((int)writer.position64); } + private long position64; + private static void DemandSpace(int required, ProtoWriter writer) + { + // check for enough space + if ((writer.ioBuffer.Length - writer.ioIndex) < required) + { + TryFlushOrResize(required, writer); + } + } + + private static void TryFlushOrResize(int required, ProtoWriter writer) + { + if (writer.flushLock == 0) + { + Flush(writer); // try emptying the buffer + if ((writer.ioBuffer.Length - writer.ioIndex) >= required) return; + } + + // either can't empty the buffer, or that didn't help; need more space + BufferPool.ResizeAndFlushLeft(ref writer.ioBuffer, required + writer.ioIndex, 0, writer.ioIndex); + } + + /// + /// Flushes data to the underlying stream, and releases any resources. The underlying stream is *not* disposed + /// by this operation. + /// + public void Close() + { + if (depth != 0 || flushLock != 0) throw new InvalidOperationException("Unable to close stream in an incomplete state"); + Dispose(); + } + + internal void CheckDepthFlushlock() + { + if (depth != 0 || flushLock != 0) throw new InvalidOperationException("The writer is in an incomplete state"); + } + + /// + /// Get the TypeModel associated with this writer + /// + public TypeModel Model => model; + + /// + /// Writes any buffered data (if possible) to the underlying stream. + /// + /// The writer to flush + /// It is not always possible to fully flush, since some sequences + /// may require values to be back-filled into the byte-stream. + internal static void Flush(ProtoWriter writer) + { + if (writer.flushLock == 0 && writer.ioIndex != 0) + { + writer.dest.Write(writer.ioBuffer, 0, writer.ioIndex); + writer.ioIndex = 0; + } + } + + /// + /// Writes an unsigned 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + private static void WriteUInt32Variant(uint value, ProtoWriter writer) + { + DemandSpace(5, writer); + int count = 0; + do + { + writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80); + count++; + } while ((value >>= 7) != 0); + writer.ioBuffer[writer.ioIndex - 1] &= 0x7F; + writer.position64 += count; + } + +#if COREFX + static readonly Encoding encoding = Encoding.UTF8; +#else + static readonly UTF8Encoding encoding = new UTF8Encoding(); +#endif + + internal static uint Zig(int value) + { + return (uint)((value << 1) ^ (value >> 31)); + } + + internal static ulong Zig(long value) + { + return (ulong)((value << 1) ^ (value >> 63)); + } + + private static void WriteUInt64Variant(ulong value, ProtoWriter writer) + { + DemandSpace(10, writer); + int count = 0; + do + { + writer.ioBuffer[writer.ioIndex++] = (byte)((value & 0x7F) | 0x80); + count++; + } while ((value >>= 7) != 0); + writer.ioBuffer[writer.ioIndex - 1] &= 0x7F; + writer.position64 += count; + } + + /// + /// Writes a string to the stream; supported wire-types: String + /// + public static void WriteString(string value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + if (writer.wireType != WireType.String) throw CreateException(writer); + if (value == null) throw new ArgumentNullException("value"); // written header; now what? + int len = value.Length; + if (len == 0) + { + WriteUInt32Variant(0, writer); + writer.wireType = WireType.None; + return; // just a header + } + int predicted = encoding.GetByteCount(value); + WriteUInt32Variant((uint)predicted, writer); + DemandSpace(predicted, writer); + int actual = encoding.GetBytes(value, 0, value.Length, writer.ioBuffer, writer.ioIndex); + Helpers.DebugAssert(predicted == actual); + IncrementedAndReset(actual, writer); + } + + /// + /// Writes an unsigned 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteUInt64(ulong value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed64: + ProtoWriter.WriteInt64((long)value, writer); + return; + case WireType.Variant: + WriteUInt64Variant(value, writer); + writer.wireType = WireType.None; + return; + case WireType.Fixed32: + checked { ProtoWriter.WriteUInt32((uint)value, writer); } + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes a signed 64-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteInt64(long value, ProtoWriter writer) + { + byte[] buffer; + int index; + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed64: + DemandSpace(8, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + +#if NETCOREAPP2_1 + System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian(buffer.AsSpan(index, 8), value); +#else + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); + buffer[index + 4] = (byte)(value >> 32); + buffer[index + 5] = (byte)(value >> 40); + buffer[index + 6] = (byte)(value >> 48); + buffer[index + 7] = (byte)(value >> 56); +#endif + IncrementedAndReset(8, writer); + return; + case WireType.SignedVariant: + WriteUInt64Variant(Zig(value), writer); + writer.wireType = WireType.None; + return; + case WireType.Variant: + if (value >= 0) + { + WriteUInt64Variant((ulong)value, writer); + writer.wireType = WireType.None; + } + else + { + DemandSpace(10, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + buffer[index] = (byte)(value | 0x80); + buffer[index + 1] = (byte)((int)(value >> 7) | 0x80); + buffer[index + 2] = (byte)((int)(value >> 14) | 0x80); + buffer[index + 3] = (byte)((int)(value >> 21) | 0x80); + buffer[index + 4] = (byte)((int)(value >> 28) | 0x80); + buffer[index + 5] = (byte)((int)(value >> 35) | 0x80); + buffer[index + 6] = (byte)((int)(value >> 42) | 0x80); + buffer[index + 7] = (byte)((int)(value >> 49) | 0x80); + buffer[index + 8] = (byte)((int)(value >> 56) | 0x80); + buffer[index + 9] = 0x01; // sign bit + IncrementedAndReset(10, writer); + } + return; + case WireType.Fixed32: + checked { WriteInt32((int)value, writer); } + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteUInt32(uint value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + switch (writer.wireType) + { + case WireType.Fixed32: + ProtoWriter.WriteInt32((int)value, writer); + return; + case WireType.Fixed64: + ProtoWriter.WriteInt64((int)value, writer); + return; + case WireType.Variant: + WriteUInt32Variant(value, writer); + writer.wireType = WireType.None; + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes a signed 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteInt16(short value, ProtoWriter writer) + { + ProtoWriter.WriteInt32(value, writer); + } + + /// + /// Writes an unsigned 16-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteUInt16(ushort value, ProtoWriter writer) + { + ProtoWriter.WriteUInt32(value, writer); + } + + /// + /// Writes an unsigned 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteByte(byte value, ProtoWriter writer) + { + ProtoWriter.WriteUInt32(value, writer); + } + /// + /// Writes a signed 8-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteSByte(sbyte value, ProtoWriter writer) + { + ProtoWriter.WriteInt32(value, writer); + } + + private static void WriteInt32ToBuffer(int value, byte[] buffer, int index) + { +#if NETCOREAPP2_1 + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(index, 4), value); +#else + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); +#endif + } + + /// + /// Writes a signed 32-bit integer to the stream; supported wire-types: Variant, Fixed32, Fixed64, SignedVariant + /// + public static void WriteInt32(int value, ProtoWriter writer) + { + byte[] buffer; + int index; + if (writer == null) throw new ArgumentNullException(nameof(writer)); + switch (writer.wireType) + { + case WireType.Fixed32: + DemandSpace(4, writer); + WriteInt32ToBuffer(value, writer.ioBuffer, writer.ioIndex); + IncrementedAndReset(4, writer); + return; + case WireType.Fixed64: + DemandSpace(8, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + buffer[index] = (byte)value; + buffer[index + 1] = (byte)(value >> 8); + buffer[index + 2] = (byte)(value >> 16); + buffer[index + 3] = (byte)(value >> 24); + buffer[index + 4] = buffer[index + 5] = + buffer[index + 6] = buffer[index + 7] = 0; + IncrementedAndReset(8, writer); + return; + case WireType.SignedVariant: + WriteUInt32Variant(Zig(value), writer); + writer.wireType = WireType.None; + return; + case WireType.Variant: + if (value >= 0) + { + WriteUInt32Variant((uint)value, writer); + writer.wireType = WireType.None; + } + else + { + DemandSpace(10, writer); + buffer = writer.ioBuffer; + index = writer.ioIndex; + buffer[index] = (byte)(value | 0x80); + buffer[index + 1] = (byte)((value >> 7) | 0x80); + buffer[index + 2] = (byte)((value >> 14) | 0x80); + buffer[index + 3] = (byte)((value >> 21) | 0x80); + buffer[index + 4] = (byte)((value >> 28) | 0x80); + buffer[index + 5] = buffer[index + 6] = + buffer[index + 7] = buffer[index + 8] = (byte)0xFF; + buffer[index + 9] = (byte)0x01; + IncrementedAndReset(10, writer); + } + return; + default: + throw CreateException(writer); + } + } + + /// + /// Writes a double-precision number to the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + + static void WriteDouble(double value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + switch (writer.wireType) + { + case WireType.Fixed32: + float f = (float)value; + if (float.IsInfinity(f) && !double.IsInfinity(value)) + { + throw new OverflowException(); + } + ProtoWriter.WriteSingle(f, writer); + return; + case WireType.Fixed64: +#if FEAT_SAFE + ProtoWriter.WriteInt64(BitConverter.ToInt64(BitConverter.GetBytes(value), 0), writer); +#else + ProtoWriter.WriteInt64(*(long*)&value, writer); +#endif + return; + default: + throw CreateException(writer); + } + } + /// + /// Writes a single-precision number to the stream; supported wire-types: Fixed32, Fixed64 + /// + public +#if !FEAT_SAFE + unsafe +#endif + static void WriteSingle(float value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + switch (writer.wireType) + { + case WireType.Fixed32: +#if FEAT_SAFE + ProtoWriter.WriteInt32(BitConverter.ToInt32(BitConverter.GetBytes(value), 0), writer); +#else + ProtoWriter.WriteInt32(*(int*)&value, writer); +#endif + return; + case WireType.Fixed64: + ProtoWriter.WriteDouble((double)value, writer); + return; + default: + throw CreateException(writer); + } + } + + /// + /// Throws an exception indicating that the given enum cannot be mapped to a serialized value. + /// + public static void ThrowEnumException(ProtoWriter writer, object enumValue) + { + if (writer == null) throw new ArgumentNullException("writer"); + string rhs = enumValue == null ? "" : (enumValue.GetType().FullName + "." + enumValue.ToString()); + throw new ProtoException("No wire-value is mapped to the enum " + rhs + " at position " + writer.position64.ToString()); + } + + // general purpose serialization exception message + internal static Exception CreateException(ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException("writer"); + return new ProtoException("Invalid serialization operation with wire-type " + writer.wireType.ToString() + " at position " + writer.position64.ToString()); + } + + /// + /// Writes a boolean to the stream; supported wire-types: Variant, Fixed32, Fixed64 + /// + public static void WriteBoolean(bool value, ProtoWriter writer) + { + ProtoWriter.WriteUInt32(value ? (uint)1 : (uint)0, writer); + } + + /// + /// Copies any extension data stored for the instance to the underlying stream + /// + public static void AppendExtensionData(IExtensible instance, ProtoWriter writer) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + // we expect the writer to be raw here; the extension data will have the + // header detail, so we'll copy it implicitly + if (writer.wireType != WireType.None) throw CreateException(writer); + + IExtension extn = instance.GetExtensionObject(false); + if (extn != null) + { + // unusually we *don't* want "using" here; the "finally" does that, with + // the extension object being responsible for disposal etc + Stream source = extn.BeginQuery(); + try + { + CopyRawFromStream(source, writer); + } + finally { extn.EndQuery(source); } + } + } + + private int packedFieldNumber; + /// + /// Used for packed encoding; indicates that the next field should be skipped rather than + /// a field header written. Note that the field number must match, else an exception is thrown + /// when the attempt is made to write the (incorrect) field. The wire-type is taken from the + /// subsequent call to WriteFieldHeader. Only primitive types can be packed. + /// + public static void SetPackedField(int fieldNumber, ProtoWriter writer) + { + if (fieldNumber <= 0) throw new ArgumentOutOfRangeException(nameof(fieldNumber)); + if (writer == null) throw new ArgumentNullException(nameof(writer)); + writer.packedFieldNumber = fieldNumber; + } + + /// + /// Used for packed encoding; explicitly reset the packed field marker; this is not required + /// if using StartSubItem/EndSubItem + /// + public static void ClearPackedField(int fieldNumber, ProtoWriter writer) + { + if (fieldNumber != writer.packedFieldNumber) + throw new InvalidOperationException("Field mismatch during packed encoding; expected " + writer.packedFieldNumber.ToString() + " but received " + fieldNumber.ToString()); + writer.packedFieldNumber = 0; + } + + /// + /// Used for packed encoding; writes the length prefix using fixed sizes rather than using + /// buffering. Only valid for fixed-32 and fixed-64 encoding. + /// + public static void WritePackedPrefix(int elementCount, WireType wireType, ProtoWriter writer) + { + if (writer.WireType != WireType.String) throw new InvalidOperationException("Invalid wire-type: " + writer.WireType); + if (elementCount < 0) throw new ArgumentOutOfRangeException(nameof(elementCount)); + ulong bytes; + switch (wireType) + { + // use long in case very large arrays are enabled + case WireType.Fixed32: bytes = ((ulong)elementCount) << 2; break; // x4 + case WireType.Fixed64: bytes = ((ulong)elementCount) << 3; break; // x8 + default: + throw new ArgumentOutOfRangeException(nameof(wireType), "Invalid wire-type: " + wireType); + } + WriteUInt64Variant(bytes, writer); + writer.wireType = WireType.None; + } + + internal string SerializeType(Type type) + { + return TypeModel.SerializeType(model, type); + } + + /// + /// Specifies a known root object to use during reference-tracked serialization + /// + public void SetRootObject(object value) + { + NetCache.SetKeyedObject(NetObjectCache.Root, value); + } + + /// + /// Writes a Type to the stream, using the model's DynamicTypeFormatting if appropriate; supported wire-types: String + /// + public static void WriteType(Type value, ProtoWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + WriteString(writer.SerializeType(value), writer); + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoWriter.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoWriter.cs.meta new file mode 100644 index 00000000..5b91b672 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ProtoWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 63b2636e44dc3824ca2dbc35316e96ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SerializationContext.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SerializationContext.cs new file mode 100644 index 00000000..80b76afa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SerializationContext.cs @@ -0,0 +1,76 @@ +using System; + +namespace ProtoBuf +{ + /// + /// Additional information about a serialization operation + /// + public sealed class SerializationContext + { + private bool frozen; + internal void Freeze() { frozen = true; } + private void ThrowIfFrozen() { if (frozen) throw new InvalidOperationException("The serialization-context cannot be changed once it is in use"); } + private object context; + /// + /// Gets or sets a user-defined object containing additional information about this serialization/deserialization operation. + /// + public object Context + { + get { return context; } + set { if (context != value) { ThrowIfFrozen(); context = value; } } + } + + private static readonly SerializationContext @default; + + static SerializationContext() + { + @default = new SerializationContext(); + @default.Freeze(); + } + /// + /// A default SerializationContext, with minimal information. + /// + internal static SerializationContext Default => @default; +#if PLAT_BINARYFORMATTER + +#if !(COREFX || PROFILE259) + private System.Runtime.Serialization.StreamingContextStates state = System.Runtime.Serialization.StreamingContextStates.Persistence; + /// + /// Gets or sets the source or destination of the transmitted data. + /// + public System.Runtime.Serialization.StreamingContextStates State + { + get { return state; } + set { if (state != value) { ThrowIfFrozen(); state = value; } } + } +#endif + /// + /// Convert a SerializationContext to a StreamingContext + /// + public static implicit operator System.Runtime.Serialization.StreamingContext(SerializationContext ctx) + { +#if COREFX + return new System.Runtime.Serialization.StreamingContext(); +#else + if (ctx == null) return new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence); + return new System.Runtime.Serialization.StreamingContext(ctx.state, ctx.context); +#endif + } + /// + /// Convert a StreamingContext to a SerializationContext + /// + public static implicit operator SerializationContext (System.Runtime.Serialization.StreamingContext ctx) + { + SerializationContext result = new SerializationContext(); + +#if !(COREFX || PROFILE259) + result.Context = ctx.Context; + result.State = ctx.State; +#endif + + return result; + } +#endif + } + +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SerializationContext.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SerializationContext.cs.meta new file mode 100644 index 00000000..9bd8dccb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SerializationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9361aaa524d95b14fbf398ba5bc075a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializer.cs new file mode 100644 index 00000000..8a4c38af --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializer.cs @@ -0,0 +1,514 @@ +using ProtoBuf.Meta; +using System; +using System.IO; +using System.Collections.Generic; +using System.Reflection; + +namespace ProtoBuf +{ + /// + /// Provides protocol-buffer serialization capability for concrete, attributed types. This + /// is a *default* model, but custom serializer models are also supported. + /// + /// + /// Protocol-buffer serialization is a compact binary format, designed to take + /// advantage of sparse data and knowledge of specific data types; it is also + /// extensible, allowing a type to be deserialized / merged even if some data is + /// not recognised. + /// + public static class Serializer + { +#if !NO_RUNTIME + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for + /// The .proto definition as a string + public static string GetProto() => GetProto(ProtoSyntax.Proto2); + + /// + /// Suggest a .proto definition for the given type + /// + /// The type to generate a .proto definition for + /// The .proto definition as a string + public static string GetProto(ProtoSyntax syntax) + { + return RuntimeTypeModel.Default.GetSchema(RuntimeTypeModel.Default.MapType(typeof(T)), syntax); + } + /// + /// Create a deep clone of the supplied instance; any sub-items are also cloned. + /// + public static T DeepClone(T instance) + { + return instance == null ? instance : (T)RuntimeTypeModel.Default.DeepClone(instance); + } + + /// + /// Applies a protocol-buffer stream to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public static T Merge(Stream source, T instance) + { + return (T)RuntimeTypeModel.Default.Deserialize(source, instance, typeof(T)); + } + + /// + /// Creates a new instance from a protocol-buffer stream + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// A new, initialized instance. + public static T Deserialize(Stream source) + { + return (T)RuntimeTypeModel.Default.Deserialize(source, null, typeof(T)); + } + + /// + /// Creates a new instance from a protocol-buffer stream + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// A new, initialized instance. + public static object Deserialize(Type type, Stream source) + { + return RuntimeTypeModel.Default.Deserialize(source, null, type); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + public static void Serialize(Stream destination, T instance) + { + if (instance != null) + { + RuntimeTypeModel.Default.Serialize(destination, instance); + } + } + + /// + /// Serializes a given instance and deserializes it as a different type; + /// this can be used to translate between wire-compatible objects (where + /// two .NET types represent the same data), or to promote/demote a type + /// through an inheritance hierarchy. + /// + /// No assumption of compatibility is made between the types. + /// The type of the object being copied. + /// The type of the new object to be created. + /// The existing instance to use as a template. + /// A new instane of type TNewType, with the data from TOldType. + public static TTo ChangeType(TFrom instance) + { + using (var ms = new MemoryStream()) + { + Serialize(ms, instance); + ms.Position = 0; + return Deserialize(ms); + } + } +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// The destination SerializationInfo to write to. + public static void Serialize(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + Serialize(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance); + } + /// + /// Writes a protocol-buffer representation of the given instance to the supplied SerializationInfo. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// The destination SerializationInfo to write to. + /// Additional information about this serialization operation. + public static void Serialize(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization) + if (info == null) throw new ArgumentNullException("info"); + if (instance == null) throw new ArgumentNullException("instance"); + if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance"); + using (MemoryStream ms = new MemoryStream()) + { + RuntimeTypeModel.Default.Serialize(ms, instance, context); + info.AddValue(ProtoBinaryField, ms.ToArray()); + } + } +#endif +#if PLAT_XMLSERIALIZER + /// + /// Writes a protocol-buffer representation of the given instance to the supplied XmlWriter. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// The destination XmlWriter to write to. + public static void Serialize(System.Xml.XmlWriter writer, T instance) where T : System.Xml.Serialization.IXmlSerializable + { + if (writer == null) throw new ArgumentNullException("writer"); + if (instance == null) throw new ArgumentNullException("instance"); + + using (MemoryStream ms = new MemoryStream()) + { + Serializer.Serialize(ms, instance); + writer.WriteBase64(Helpers.GetBuffer(ms), 0, (int)ms.Length); + } + } + /// + /// Applies a protocol-buffer from an XmlReader to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (cannot be null). + /// The XmlReader containing the data to apply to the instance (cannot be null). + public static void Merge(System.Xml.XmlReader reader, T instance) where T : System.Xml.Serialization.IXmlSerializable + { + if (reader == null) throw new ArgumentNullException("reader"); + if (instance == null) throw new ArgumentNullException("instance"); + + const int LEN = 4096; + byte[] buffer = new byte[LEN]; + int read; + using (MemoryStream ms = new MemoryStream()) + { + int depth = reader.Depth; + while(reader.Read() && reader.Depth > depth) + { + if (reader.NodeType == System.Xml.XmlNodeType.Text) + { + while ((read = reader.ReadContentAsBase64(buffer, 0, LEN)) > 0) + { + ms.Write(buffer, 0, read); + } + if (reader.Depth <= depth) break; + } + } + ms.Position = 0; + Serializer.Merge(ms, instance); + } + } +#endif + + private const string ProtoBinaryField = "proto"; +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Applies a protocol-buffer from a SerializationInfo to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (cannot be null). + /// The SerializationInfo containing the data to apply to the instance (cannot be null). + public static void Merge(System.Runtime.Serialization.SerializationInfo info, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + Merge(info, new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence), instance); + } + /// + /// Applies a protocol-buffer from a SerializationInfo to an existing instance. + /// + /// The type being merged. + /// The existing instance to be modified (cannot be null). + /// The SerializationInfo containing the data to apply to the instance (cannot be null). + /// Additional information about this serialization operation. + public static void Merge(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, T instance) where T : class, System.Runtime.Serialization.ISerializable + { + // note: also tried byte[]... it doesn't perform hugely well with either (compared to regular serialization) + if (info == null) throw new ArgumentNullException("info"); + if (instance == null) throw new ArgumentNullException("instance"); + if (instance.GetType() != typeof(T)) throw new ArgumentException("Incorrect type", "instance"); + + byte[] buffer = (byte[])info.GetValue(ProtoBinaryField, typeof(byte[])); + using (MemoryStream ms = new MemoryStream(buffer)) + { + T result = (T)RuntimeTypeModel.Default.Deserialize(ms, instance, typeof(T), context); + if (!ReferenceEquals(result, instance)) + { + throw new ProtoException("Deserialization changed the instance; cannot succeed."); + } + } + } +#endif + + /// + /// Precompiles the serializer for a given type. + /// + public static void PrepareSerializer() + { + NonGeneric.PrepareSerializer(typeof(T)); + } + +#if PLAT_BINARYFORMATTER && !(COREFX || PROFILE259) + /// + /// Creates a new IFormatter that uses protocol-buffer [de]serialization. + /// + /// The type of object to be [de]deserialized by the formatter. + /// A new IFormatter to be used during [de]serialization. + public static System.Runtime.Serialization.IFormatter CreateFormatter() + { + return RuntimeTypeModel.Default.CreateFormatter(typeof(T)); + } +#endif + /// + /// Reads a sequence of consecutive length-prefixed items from a stream, using + /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag + /// are directly comparable to serializing multiple items in succession + /// (use the tag to emulate the implicit behavior + /// when serializing a list/array). When a tag is + /// specified, any records with different tags are silently omitted. The + /// tag is ignored. The tag is ignored for fixed-length prefixes. + /// + /// The type of object to deserialize. + /// The binary stream containing the serialized records. + /// The prefix style used in the data. + /// The tag of records to return (if non-positive, then no tag is + /// expected and all records are returned). + /// The sequence of deserialized objects. + public static IEnumerable DeserializeItems(Stream source, PrefixStyle style, int fieldNumber) + { + return RuntimeTypeModel.Default.DeserializeItems(source, style, fieldNumber); + } + + /// + /// Creates a new instance from a protocol-buffer stream that has a length-prefix + /// on data (to assist with network IO). + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// How to encode the length prefix. + /// A new, initialized instance. + public static T DeserializeWithLengthPrefix(Stream source, PrefixStyle style) + { + return DeserializeWithLengthPrefix(source, style, 0); + } + + /// + /// Creates a new instance from a protocol-buffer stream that has a length-prefix + /// on data (to assist with network IO). + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// How to encode the length prefix. + /// The expected tag of the item (only used with base-128 prefix style). + /// A new, initialized instance. + public static T DeserializeWithLengthPrefix(Stream source, PrefixStyle style, int fieldNumber) + { + RuntimeTypeModel model = RuntimeTypeModel.Default; + return (T)model.DeserializeWithLengthPrefix(source, null, model.MapType(typeof(T)), style, fieldNumber); + } + + /// + /// Applies a protocol-buffer stream to an existing instance, using length-prefixed + /// data - useful with network IO. + /// + /// The type being merged. + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public static T MergeWithLengthPrefix(Stream source, T instance, PrefixStyle style) + { + RuntimeTypeModel model = RuntimeTypeModel.Default; + return (T)model.DeserializeWithLengthPrefix(source, instance, model.MapType(typeof(T)), style, 0); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + public static void SerializeWithLengthPrefix(Stream destination, T instance, PrefixStyle style) + { + SerializeWithLengthPrefix(destination, instance, style, 0); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The type being serialized. + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + public static void SerializeWithLengthPrefix(Stream destination, T instance, PrefixStyle style, int fieldNumber) + { + RuntimeTypeModel model = RuntimeTypeModel.Default; + model.SerializeWithLengthPrefix(destination, instance, model.MapType(typeof(T)), style, fieldNumber); + } + + /// Indicates the number of bytes expected for the next message. + /// The stream containing the data to investigate for a length. + /// The algorithm used to encode the length. + /// The length of the message, if it could be identified. + /// True if a length could be obtained, false otherwise. + public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length) + { + length = ProtoReader.ReadLengthPrefix(source, false, style, out int fieldNumber, out int bytesRead); + return bytesRead > 0; + } + + /// Indicates the number of bytes expected for the next message. + /// The buffer containing the data to investigate for a length. + /// The offset of the first byte to read from the buffer. + /// The number of bytes to read from the buffer. + /// The algorithm used to encode the length. + /// The length of the message, if it could be identified. + /// True if a length could be obtained, false otherwise. + public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length) + { + using (Stream source = new MemoryStream(buffer, index, count)) + { + return TryReadLengthPrefix(source, style, out length); + } + } +#endif + /// + /// The field number that is used as a default when serializing/deserializing a list of objects. + /// The data is treated as repeated message with field number 1. + /// + public const int ListItemTag = 1; + + +#if !NO_RUNTIME + /// + /// Provides non-generic access to the default serializer. + /// + public static class NonGeneric + { + /// + /// Create a deep clone of the supplied instance; any sub-items are also cloned. + /// + public static object DeepClone(object instance) + { + return instance == null ? null : RuntimeTypeModel.Default.DeepClone(instance); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream. + /// + /// The existing instance to be serialized (cannot be null). + /// The destination stream to write to. + public static void Serialize(Stream dest, object instance) + { + if (instance != null) + { + RuntimeTypeModel.Default.Serialize(dest, instance); + } + } + + /// + /// Creates a new instance from a protocol-buffer stream + /// + /// The type to be created. + /// The binary stream to apply to the new instance (cannot be null). + /// A new, initialized instance. + public static object Deserialize(Type type, Stream source) + { + return RuntimeTypeModel.Default.Deserialize(source, null, type); + } + + /// Applies a protocol-buffer stream to an existing instance. + /// The existing instance to be modified (cannot be null). + /// The binary stream to apply to the instance (cannot be null). + /// The updated instance + public static object Merge(Stream source, object instance) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + return RuntimeTypeModel.Default.Deserialize(source, instance, instance.GetType(), null); + } + + /// + /// Writes a protocol-buffer representation of the given instance to the supplied stream, + /// with a length-prefix. This is useful for socket programming, + /// as DeserializeWithLengthPrefix/MergeWithLengthPrefix can be used to read the single object back + /// from an ongoing stream. + /// + /// The existing instance to be serialized (cannot be null). + /// How to encode the length prefix. + /// The destination stream to write to. + /// The tag used as a prefix to each record (only used with base-128 style prefixes). + public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber) + { + if (instance == null) throw new ArgumentNullException(nameof(instance)); + RuntimeTypeModel model = RuntimeTypeModel.Default; + model.SerializeWithLengthPrefix(destination, instance, model.MapType(instance.GetType()), style, fieldNumber); + } + /// + /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed + /// data - useful with network IO. + /// + /// The existing instance to be modified (can be null). + /// The binary stream to apply to the instance (cannot be null). + /// How to encode the length prefix. + /// Used to resolve types on a per-field basis. + /// The updated instance; this may be different to the instance argument if + /// either the original instance was null, or the stream defines a known sub-type of the + /// original instance. + public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value) + { + value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver); + return value != null; + } + + /// + /// Indicates whether the supplied type is explicitly modelled by the model + /// + public static bool CanSerialize(Type type) => RuntimeTypeModel.Default.IsDefined(type); + + /// + /// Precompiles the serializer for a given type. + /// + public static void PrepareSerializer(Type t) + { +#if FEAT_COMPILER + RuntimeTypeModel model = RuntimeTypeModel.Default; + model[model.MapType(t)].CompileInPlace(); +#endif + } + } + + /// + /// Global switches that change the behavior of protobuf-net + /// + public static class GlobalOptions + { + /// + /// + /// + [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)] + public static bool InferTagFromName + { + get { return RuntimeTypeModel.Default.InferTagFromNameDefault; } + set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; } + } + } +#endif + /// + /// Maps a field-number to a type + /// + public delegate Type TypeResolver(int fieldNumber); + + /// + /// Releases any internal buffers that have been reserved for efficiency; this does not affect any serialization + /// operations; simply: it can be used (optionally) to release the buffers for garbage collection (at the expense + /// of having to re-allocate a new buffer for the next operation, rather than re-use prior buffers). + /// + public static void FlushPool() + { + BufferPool.Flush(); + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializer.cs.meta new file mode 100644 index 00000000..63cf57db --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dbd7fc6a1f1a0e34b8a1bce7e93c4f61 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers.meta new file mode 100644 index 00000000..569acba6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 90bd17a736284764ca22da41661472de +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs new file mode 100644 index 00000000..cad005f1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs @@ -0,0 +1,310 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class ArrayDecorator : ProtoDecoratorBase + { + private readonly int fieldNumber; + private const byte + OPTIONS_WritePacked = 1, + OPTIONS_OverwriteList = 2, + OPTIONS_SupportNull = 4; + private readonly byte options; + private readonly WireType packedWireType; + public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull) + : base(tail) + { + Helpers.DebugAssert(arrayType != null, "arrayType should be non-null"); + Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName); + this.itemType = arrayType.GetElementType(); + Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType); + + Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType + || (Tail.ExpectedType == model.MapType(typeof(object)) && !Helpers.IsValueType(underlyingItemType)), "invalid tail"); + Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer"); + if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); + if (!ListDecorator.CanPack(packedWireType)) + { + if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); + packedWireType = WireType.None; + } + this.fieldNumber = fieldNumber; + this.packedWireType = packedWireType; + if (writePacked) options |= OPTIONS_WritePacked; + if (overwriteList) options |= OPTIONS_OverwriteList; + if (supportNull) options |= OPTIONS_SupportNull; + this.arrayType = arrayType; + } + readonly Type arrayType, itemType; // this is, for example, typeof(int[]) + public override Type ExpectedType { get { return arrayType; } } + public override bool RequiresOldValue { get { return AppendToCollection; } } + public override bool ReturnsValue { get { return true; } } + private bool CanUsePackedPrefix() => CanUsePackedPrefix(packedWireType, itemType); + + internal static bool CanUsePackedPrefix(WireType packedWireType, Type itemType) + { + // needs to be a suitably simple type *and* be definitely not nullable + switch (packedWireType) + { + case WireType.Fixed32: + case WireType.Fixed64: + break; + default: + return false; // nope + } + if (!Helpers.IsValueType(itemType)) return false; + return Helpers.GetUnderlyingType(itemType) == null; + } + +#if FEAT_COMPILER + protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + // int i and T[] arr + using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom)) + using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + bool writePacked = (options & OPTIONS_WritePacked) != 0; + bool fixedLengthPacked = writePacked && CanUsePackedPrefix(); + + using (Compiler.Local token = (writePacked && !fixedLengthPacked) ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null) + { + Type mappedWriter = ctx.MapType(typeof(ProtoWriter)); + if (writePacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)WireType.String); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("WriteFieldHeader")); + + if (fixedLengthPacked) + { + // write directly - no need for buffering + ctx.LoadLength(arr, false); + ctx.LoadValue((int)packedWireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("WritePackedPrefix")); + } + else + { + ctx.LoadValue(arr); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("StartSubItem")); + ctx.StoreValue(token); + } + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("SetPackedField")); + } + EmitWriteArrayLoop(ctx, i, arr); + + if (writePacked) + { + if (fixedLengthPacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("ClearPackedField")); + } + else + { + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(mappedWriter.GetMethod("EndSubItem")); + } + } + } + } + } + + private void EmitWriteArrayLoop(Compiler.CompilerContext ctx, Compiler.Local i, Compiler.Local arr) + { + // i = 0 + ctx.LoadValue(0); + ctx.StoreValue(i); + + // range test is last (to minimise branches) + Compiler.CodeLabel loopTest = ctx.DefineLabel(), processItem = ctx.DefineLabel(); + ctx.Branch(loopTest, false); + ctx.MarkLabel(processItem); + + // {...} + ctx.LoadArrayValue(arr, i); + if (SupportNull) + { + Tail.EmitWrite(ctx, null); + } + else + { + ctx.WriteNullCheckedTail(itemType, Tail, null); + } + + // i++ + ctx.LoadValue(i); + ctx.LoadValue(1); + ctx.Add(); + ctx.StoreValue(i); + + // i < arr.Length + ctx.MarkLabel(loopTest); + ctx.LoadValue(i); + ctx.LoadLength(arr, false); + ctx.BranchIfLess(processItem, false); + } +#endif + private bool AppendToCollection => (options & OPTIONS_OverwriteList) == 0; + + private bool SupportNull { get { return (options & OPTIONS_SupportNull) != 0; } } + + public override void Write(object value, ProtoWriter dest) + { + IList arr = (IList)value; + int len = arr.Count; + SubItemToken token; + bool writePacked = (options & OPTIONS_WritePacked) != 0; + bool fixedLengthPacked = writePacked && CanUsePackedPrefix(); + + if (writePacked) + { + ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest); + + if (fixedLengthPacked) + { + ProtoWriter.WritePackedPrefix(arr.Count, packedWireType, dest); + token = new SubItemToken(); // default + } + else + { + token = ProtoWriter.StartSubItem(value, dest); + } + ProtoWriter.SetPackedField(fieldNumber, dest); + } + else + { + token = new SubItemToken(); // default + } + bool checkForNull = !SupportNull; + for (int i = 0; i < len; i++) + { + object obj = arr[i]; + if (checkForNull && obj == null) { throw new NullReferenceException(); } + Tail.Write(obj, dest); + } + if (writePacked) + { + if (fixedLengthPacked) + { + ProtoWriter.ClearPackedField(fieldNumber, dest); + } + else + { + ProtoWriter.EndSubItem(token, dest); + } + } + } + public override object Read(object value, ProtoReader source) + { + int field = source.FieldNumber; + BasicList list = new BasicList(); + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + while (ProtoReader.HasSubValue(packedWireType, source)) + { + list.Add(Tail.Read(null, source)); + } + ProtoReader.EndSubItem(token, source); + } + else + { + do + { + list.Add(Tail.Read(null, source)); + } while (source.TryReadFieldHeader(field)); + } + int oldLen = AppendToCollection ? ((value == null ? 0 : ((Array)value).Length)) : 0; + Array result = Array.CreateInstance(itemType, oldLen + list.Count); + if (oldLen != 0) ((Array)value).CopyTo(result, 0); + list.CopyTo(result, oldLen); + return result; + } + +#if FEAT_COMPILER + protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + Type listType; + listType = ctx.MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType); + Type expected = ExpectedType; + using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(expected, valueFrom) : null) + using (Compiler.Local newArr = new Compiler.Local(ctx, expected)) + using (Compiler.Local list = new Compiler.Local(ctx, listType)) + { + ctx.EmitCtor(listType); + ctx.StoreValue(list); + ListDecorator.EmitReadList(ctx, list, Tail, listType.GetMethod("Add"), packedWireType, false); + + // leave this "using" here, as it can share the "FieldNumber" local with EmitReadList + using (Compiler.Local oldLen = AppendToCollection ? new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))) : null) + { + Type[] copyToArrayInt32Args = new Type[] { ctx.MapType(typeof(Array)), ctx.MapType(typeof(int)) }; + + if (AppendToCollection) + { + ctx.LoadLength(oldArr, true); + ctx.CopyValue(); + ctx.StoreValue(oldLen); + + ctx.LoadAddress(list, listType); + ctx.LoadValue(listType.GetProperty("Count")); + ctx.Add(); + ctx.CreateArray(itemType, null); // length is on the stack + ctx.StoreValue(newArr); + + ctx.LoadValue(oldLen); + Compiler.CodeLabel nothingToCopy = ctx.DefineLabel(); + ctx.BranchIfFalse(nothingToCopy, true); + ctx.LoadValue(oldArr); + ctx.LoadValue(newArr); + ctx.LoadValue(0); // index in target + + ctx.EmitCall(expected.GetMethod("CopyTo", copyToArrayInt32Args)); + ctx.MarkLabel(nothingToCopy); + + ctx.LoadValue(list); + ctx.LoadValue(newArr); + ctx.LoadValue(oldLen); + + } + else + { + ctx.LoadAddress(list, listType); + ctx.LoadValue(listType.GetProperty("Count")); + ctx.CreateArray(itemType, null); + ctx.StoreValue(newArr); + + ctx.LoadAddress(list, listType); + ctx.LoadValue(newArr); + ctx.LoadValue(0); + } + + copyToArrayInt32Args[0] = expected; // // prefer: CopyTo(T[], int) + MethodInfo copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args); + if (copyTo == null) + { // fallback: CopyTo(Array, int) + copyToArrayInt32Args[1] = ctx.MapType(typeof(Array)); + copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args); + } + ctx.EmitCall(copyTo); + } + ctx.LoadValue(newArr); + } + + + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta new file mode 100644 index 00000000..6958590e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ArrayDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3689dde3ac5fd544a9e66158c9713872 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs new file mode 100644 index 00000000..40b2b89e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs @@ -0,0 +1,59 @@ +#if !NO_RUNTIME +using System; +#if COREFX +using System.Reflection; +#endif +#if FEAT_COMPILER +using System.Reflection.Emit; +#endif + +namespace ProtoBuf.Serializers +{ + sealed class BlobSerializer : IProtoSerializer + { + public Type ExpectedType { get { return expectedType; } } + + static readonly Type expectedType = typeof(byte[]); + + public BlobSerializer(ProtoBuf.Meta.TypeModel model, bool overwriteList) + { + this.overwriteList = overwriteList; + } + + private readonly bool overwriteList; + + public object Read(object value, ProtoReader source) + { + return ProtoReader.AppendBytes(overwriteList ? null : (byte[])value, source); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteBytes((byte[])value, dest); + } + + bool IProtoSerializer.RequiresOldValue { get { return !overwriteList; } } + bool IProtoSerializer.ReturnsValue { get { return true; } } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteBytes", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (overwriteList) + { + ctx.LoadNullRef(); + } + else + { + ctx.LoadValue(valueFrom); + } + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)) + .GetMethod("AppendBytes")); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta new file mode 100644 index 00000000..49dd403c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BlobSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c04427a4647d6314e82d8a63882dcb8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs new file mode 100644 index 00000000..c64886ae --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs @@ -0,0 +1,41 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class BooleanSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(bool); + + public BooleanSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteBoolean((bool)value, dest); + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadBoolean(); + } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteBoolean", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadBoolean", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta new file mode 100644 index 00000000..f9823840 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/BooleanSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b73f749f97802947812dc66867ed1f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs new file mode 100644 index 00000000..e44a83c0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class ByteSerializer : IProtoSerializer + { + public Type ExpectedType { get { return expectedType; } } + + static readonly Type expectedType = typeof(byte); + + public ByteSerializer(ProtoBuf.Meta.TypeModel model) { } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteByte((byte)value, dest); + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadByte(); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteByte", valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadByte", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta new file mode 100644 index 00000000..23a58b1c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ByteSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c17779da4eb6b1d489531294afcb2a32 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CharSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CharSerializer.cs new file mode 100644 index 00000000..3bc30d04 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CharSerializer.cs @@ -0,0 +1,32 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class CharSerializer : UInt16Serializer + { + static readonly Type expectedType = typeof(char); + + public CharSerializer(ProtoBuf.Meta.TypeModel model) : base(model) + { + + } + + public override Type ExpectedType => expectedType; + + public override void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt16((ushort)(char)value, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return (char)source.ReadUInt16(); + } + + // no need for any special IL here; ushort and char are + // interchangeable as long as there is no boxing/unboxing + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta new file mode 100644 index 00000000..0424efcf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CharSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 526090cb730f087469b7f20948f4932a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs new file mode 100644 index 00000000..1ec30273 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs @@ -0,0 +1,88 @@ +#if FEAT_COMPILER +using System; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class CompiledSerializer : IProtoTypeSerializer + { + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return head.HasCallbacks(callbackType); // these routes only used when bits of the model not compiled + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return head.CanCreateInstance(); + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return head.CreateInstance(source); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + head.Callback(value, callbackType, context); // these routes only used when bits of the model not compiled + } + + public static CompiledSerializer Wrap(IProtoTypeSerializer head, TypeModel model) + { + CompiledSerializer result = head as CompiledSerializer; + if (result == null) + { + result = new CompiledSerializer(head, model); + Helpers.DebugAssert(((IProtoTypeSerializer)result).ExpectedType == head.ExpectedType); + } + return result; + } + + private readonly IProtoTypeSerializer head; + private readonly Compiler.ProtoSerializer serializer; + private readonly Compiler.ProtoDeserializer deserializer; + + private CompiledSerializer(IProtoTypeSerializer head, TypeModel model) + { + this.head = head; + serializer = Compiler.CompilerContext.BuildSerializer(head, model); + deserializer = Compiler.CompilerContext.BuildDeserializer(head, model); + } + + bool IProtoSerializer.RequiresOldValue => head.RequiresOldValue; + + bool IProtoSerializer.ReturnsValue => head.ReturnsValue; + + Type IProtoSerializer.ExpectedType => head.ExpectedType; + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + serializer(value, dest); + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return deserializer(value, source); + } + + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + head.EmitWrite(ctx, valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + head.EmitRead(ctx, valueFrom); + } + + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + head.EmitCallback(ctx, valueFrom, callbackType); + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) + { + head.EmitCreateInstance(ctx); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta new file mode 100644 index 00000000..ddef8756 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/CompiledSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 90821da5568834a4682d1a42d7f66963 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs new file mode 100644 index 00000000..9755df9e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs @@ -0,0 +1,65 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + internal sealed class DateTimeSerializer : IProtoSerializer + { + private static readonly Type expectedType = typeof(DateTime); + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + bool IProtoSerializer.ReturnsValue => true; + + private readonly bool includeKind, wellKnown; + + public DateTimeSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model) + { + wellKnown = dataFormat == DataFormat.WellKnown; + includeKind = model?.SerializeDateTimeKind() == true; + } + + public object Read(object value, ProtoReader source) + { + if (wellKnown) + { + return BclHelpers.ReadTimestamp(source); + } + else + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadDateTime(source); + } + } + + public void Write(object value, ProtoWriter dest) + { + if (wellKnown) + BclHelpers.WriteTimestamp((DateTime)value, dest); + else if (includeKind) + BclHelpers.WriteDateTimeWithKind((DateTime)value, dest); + else + BclHelpers.WriteDateTime((DateTime)value, dest); + } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.WriteTimestamp) + : includeKind ? nameof(BclHelpers.WriteDateTimeWithKind) : nameof(BclHelpers.WriteDateTime), valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity) + { + if (wellKnown) ctx.LoadValue(entity); + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.ReadTimestamp) : nameof(BclHelpers.ReadDateTime), + ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta new file mode 100644 index 00000000..6757f0c0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DateTimeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dfba0a8c252b2e54c96478c9e690c7d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs new file mode 100644 index 00000000..1edc6219 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class DecimalSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(decimal); + + public DecimalSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadDecimal(source); + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteDecimal((decimal)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteDecimal", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadDecimal", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta new file mode 100644 index 00000000..f8e097a8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DecimalSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80efe6cca6916ab46b430c27dc58369c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs new file mode 100644 index 00000000..895d0c4b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs @@ -0,0 +1,259 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class DefaultValueDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private readonly object defaultValue; + public DefaultValueDecorator(TypeModel model, object defaultValue, IProtoSerializer tail) : base(tail) + { + if (defaultValue == null) throw new ArgumentNullException(nameof(defaultValue)); + Type type = model.MapType(defaultValue.GetType()); + if (type != tail.ExpectedType) + { + throw new ArgumentException("Default value is of incorrect type", "defaultValue"); + } + this.defaultValue = defaultValue; + } + + public override void Write(object value, ProtoWriter dest) + { + if (!object.Equals(value, defaultValue)) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + return Tail.Read(value, source); + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Compiler.CodeLabel done = ctx.DefineLabel(); + if (valueFrom == null) + { + ctx.CopyValue(); // on the stack + Compiler.CodeLabel needToPop = ctx.DefineLabel(); + EmitBranchIfDefaultValue(ctx, needToPop); + Tail.EmitWrite(ctx, null); + ctx.Branch(done, true); + ctx.MarkLabel(needToPop); + ctx.DiscardValue(); + } + else + { + ctx.LoadValue(valueFrom); // variable/parameter + EmitBranchIfDefaultValue(ctx, done); + Tail.EmitWrite(ctx, valueFrom); + } + ctx.MarkLabel(done); + } + private void EmitBeq(Compiler.CompilerContext ctx, Compiler.CodeLabel label, Type type) + { + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Char: + case ProtoTypeCode.Double: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.Int64: + case ProtoTypeCode.SByte: + case ProtoTypeCode.Single: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + case ProtoTypeCode.UInt64: + ctx.BranchIfEqual(label, false); + break; + default: +#if COREFX + MethodInfo method = type.GetMethod("op_Equality", new Type[] { type, type }); + if (method == null || !method.IsPublic || !method.IsStatic) method = null; +#else + MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static, + null, new Type[] { type, type }, null); +#endif + if (method == null || method.ReturnType != ctx.MapType(typeof(bool))) + { + throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName); + } + ctx.EmitCall(method); + ctx.BranchIfTrue(label, false); + break; + + } + } + private void EmitBranchIfDefaultValue(Compiler.CompilerContext ctx, Compiler.CodeLabel label) + { + Type expected = ExpectedType; + switch (Helpers.GetTypeCode(expected)) + { + case ProtoTypeCode.Boolean: + if ((bool)defaultValue) + { + ctx.BranchIfTrue(label, false); + } + else + { + ctx.BranchIfFalse(label, false); + } + break; + case ProtoTypeCode.Byte: + if ((byte)defaultValue == (byte)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(byte)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.SByte: + if ((sbyte)defaultValue == (sbyte)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(sbyte)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Int16: + if ((short)defaultValue == (short)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(short)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.UInt16: + if ((ushort)defaultValue == (ushort)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(ushort)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Int32: + if ((int)defaultValue == (int)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.UInt32: + if ((uint)defaultValue == (uint)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(uint)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Char: + if ((char)defaultValue == (char)0) + { + ctx.BranchIfFalse(label, false); + } + else + { + ctx.LoadValue((int)(char)defaultValue); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.Int64: + ctx.LoadValue((long)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.UInt64: + ctx.LoadValue((long)(ulong)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.Double: + ctx.LoadValue((double)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.Single: + ctx.LoadValue((float)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.String: + ctx.LoadValue((string)defaultValue); + EmitBeq(ctx, label, expected); + break; + case ProtoTypeCode.Decimal: + { + decimal d = (decimal)defaultValue; + ctx.LoadValue(d); + EmitBeq(ctx, label, expected); + } + break; + case ProtoTypeCode.TimeSpan: + { + TimeSpan ts = (TimeSpan)defaultValue; + if (ts == TimeSpan.Zero) + { + ctx.LoadValue(typeof(TimeSpan).GetField("Zero")); + } + else + { + ctx.LoadValue(ts.Ticks); + ctx.EmitCall(ctx.MapType(typeof(TimeSpan)).GetMethod("FromTicks")); + } + EmitBeq(ctx, label, expected); + break; + } + case ProtoTypeCode.Guid: + { + ctx.LoadValue((Guid)defaultValue); + EmitBeq(ctx, label, expected); + break; + } + case ProtoTypeCode.DateTime: + { + ctx.LoadValue(((DateTime)defaultValue).ToBinary()); + ctx.EmitCall(ctx.MapType(typeof(DateTime)).GetMethod("FromBinary")); + + EmitBeq(ctx, label, expected); + break; + } + default: + throw new NotSupportedException("Type cannot be represented as a default value: " + expected.FullName); + } + } + + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta new file mode 100644 index 00000000..7cbd6ed3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DefaultValueDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad3a3e386e17b67488f858d409d3e8a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs new file mode 100644 index 00000000..8b25523a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class DoubleSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(double); + + public DoubleSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadDouble(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteDouble((double)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteDouble", valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadDouble", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta new file mode 100644 index 00000000..cdba0a78 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/DoubleSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 65b598b3ebee04946abf8957a0f92762 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs new file mode 100644 index 00000000..78cb78a2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs @@ -0,0 +1,267 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class EnumSerializer : IProtoSerializer + { + public readonly struct EnumPair + { + public readonly object RawValue; // note that this is boxing, but I'll live with it + public readonly Enum TypedValue; // note that this is boxing, but I'll live with it + public readonly int WireValue; + public EnumPair(int wireValue, object raw, Type type) + { + WireValue = wireValue; + RawValue = raw; + TypedValue = (Enum)Enum.ToObject(type, raw); + } + } + + private readonly Type enumType; + private readonly EnumPair[] map; + public EnumSerializer(Type enumType, EnumPair[] map) + { + this.enumType = enumType ?? throw new ArgumentNullException(nameof(enumType)); + this.map = map; + if (map != null) + { + for (int i = 1; i < map.Length; i++) + for (int j = 0; j < i; j++) + { + if (map[i].WireValue == map[j].WireValue && !Equals(map[i].RawValue, map[j].RawValue)) + { + throw new ProtoException("Multiple enums with wire-value " + map[i].WireValue.ToString()); + } + if (Equals(map[i].RawValue, map[j].RawValue) && map[i].WireValue != map[j].WireValue) + { + throw new ProtoException("Multiple enums with deserialized-value " + map[i].RawValue); + } + } + + } + } + + private ProtoTypeCode GetTypeCode() + { + Type type = Helpers.GetUnderlyingType(enumType); + if (type == null) type = enumType; + return Helpers.GetTypeCode(type); + } + + public Type ExpectedType => enumType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + private int EnumToWire(object value) + { + unchecked + { + switch (GetTypeCode()) + { // unbox then convert to int + case ProtoTypeCode.Byte: return (int)(byte)value; + case ProtoTypeCode.SByte: return (int)(sbyte)value; + case ProtoTypeCode.Int16: return (int)(short)value; + case ProtoTypeCode.Int32: return (int)value; + case ProtoTypeCode.Int64: return (int)(long)value; + case ProtoTypeCode.UInt16: return (int)(ushort)value; + case ProtoTypeCode.UInt32: return (int)(uint)value; + case ProtoTypeCode.UInt64: return (int)(ulong)value; + default: throw new InvalidOperationException(); + } + } + } + + private object WireToEnum(int value) + { + unchecked + { + switch (GetTypeCode()) + { // convert from int then box + case ProtoTypeCode.Byte: return Enum.ToObject(enumType, (byte)value); + case ProtoTypeCode.SByte: return Enum.ToObject(enumType, (sbyte)value); + case ProtoTypeCode.Int16: return Enum.ToObject(enumType, (short)value); + case ProtoTypeCode.Int32: return Enum.ToObject(enumType, value); + case ProtoTypeCode.Int64: return Enum.ToObject(enumType, (long)value); + case ProtoTypeCode.UInt16: return Enum.ToObject(enumType, (ushort)value); + case ProtoTypeCode.UInt32: return Enum.ToObject(enumType, (uint)value); + case ProtoTypeCode.UInt64: return Enum.ToObject(enumType, (ulong)value); + default: throw new InvalidOperationException(); + } + } + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + int wireValue = source.ReadInt32(); + if (map == null) + { + return WireToEnum(wireValue); + } + for (int i = 0; i < map.Length; i++) + { + if (map[i].WireValue == wireValue) + { + return map[i].TypedValue; + } + } + source.ThrowEnumException(ExpectedType, wireValue); + return null; // to make compiler happy + } + + public void Write(object value, ProtoWriter dest) + { + if (map == null) + { + ProtoWriter.WriteInt32(EnumToWire(value), dest); + } + else + { + for (int i = 0; i < map.Length; i++) + { + if (object.Equals(map[i].TypedValue, value)) + { + ProtoWriter.WriteInt32(map[i].WireValue, dest); + return; + } + } + ProtoWriter.ThrowEnumException(dest, value); + } + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ProtoTypeCode typeCode = GetTypeCode(); + if (map == null) + { + ctx.LoadValue(valueFrom); + ctx.ConvertToInt32(typeCode, false); + ctx.EmitBasicWrite("WriteInt32", null); + } + else + { + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + Compiler.CodeLabel @continue = ctx.DefineLabel(); + for (int i = 0; i < map.Length; i++) + { + Compiler.CodeLabel tryNextValue = ctx.DefineLabel(), processThisValue = ctx.DefineLabel(); + ctx.LoadValue(loc); + WriteEnumValue(ctx, typeCode, map[i].RawValue); + ctx.BranchIfEqual(processThisValue, true); + ctx.Branch(tryNextValue, true); + ctx.MarkLabel(processThisValue); + ctx.LoadValue(map[i].WireValue); + ctx.EmitBasicWrite("WriteInt32", null); + ctx.Branch(@continue, false); + ctx.MarkLabel(tryNextValue); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(loc); + ctx.CastToObject(ExpectedType); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("ThrowEnumException")); + ctx.MarkLabel(@continue); + } + } + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ProtoTypeCode typeCode = GetTypeCode(); + if (map == null) + { + ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int))); + ctx.ConvertFromInt32(typeCode, false); + } + else + { + int[] wireValues = new int[map.Length]; + object[] values = new object[map.Length]; + for (int i = 0; i < map.Length; i++) + { + wireValues[i] = map[i].WireValue; + values[i] = map[i].RawValue; + } + using (Compiler.Local result = new Compiler.Local(ctx, ExpectedType)) + using (Compiler.Local wireValue = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int))); + ctx.StoreValue(wireValue); + Compiler.CodeLabel @continue = ctx.DefineLabel(); + foreach (BasicList.Group group in BasicList.GetContiguousGroups(wireValues, values)) + { + Compiler.CodeLabel tryNextGroup = ctx.DefineLabel(); + int groupItemCount = group.Items.Count; + if (groupItemCount == 1) + { + // discreet group; use an equality test + ctx.LoadValue(wireValue); + ctx.LoadValue(group.First); + Compiler.CodeLabel processThisValue = ctx.DefineLabel(); + ctx.BranchIfEqual(processThisValue, true); + ctx.Branch(tryNextGroup, false); + WriteEnumValue(ctx, typeCode, processThisValue, @continue, group.Items[0], @result); + } + else + { + // implement as a jump-table-based switch + ctx.LoadValue(wireValue); + ctx.LoadValue(group.First); + ctx.Subtract(); // jump-tables are zero-based + Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount]; + for (int i = 0; i < groupItemCount; i++) + { + jmp[i] = ctx.DefineLabel(); + } + ctx.Switch(jmp); + // write the default... + ctx.Branch(tryNextGroup, false); + for (int i = 0; i < groupItemCount; i++) + { + WriteEnumValue(ctx, typeCode, jmp[i], @continue, group.Items[i], @result); + } + } + ctx.MarkLabel(tryNextGroup); + } + // throw source.CreateEnumException(ExpectedType, wireValue); + ctx.LoadReaderWriter(); + ctx.LoadValue(ExpectedType); + ctx.LoadValue(wireValue); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("ThrowEnumException")); + ctx.MarkLabel(@continue); + ctx.LoadValue(result); + } + } + } + private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, object value) + { + switch (typeCode) + { + case ProtoTypeCode.Byte: ctx.LoadValue((int)(byte)value); break; + case ProtoTypeCode.SByte: ctx.LoadValue((int)(sbyte)value); break; + case ProtoTypeCode.Int16: ctx.LoadValue((int)(short)value); break; + case ProtoTypeCode.Int32: ctx.LoadValue((int)(int)value); break; + case ProtoTypeCode.Int64: ctx.LoadValue((long)(long)value); break; + case ProtoTypeCode.UInt16: ctx.LoadValue((int)(ushort)value); break; + case ProtoTypeCode.UInt32: ctx.LoadValue((int)(uint)value); break; + case ProtoTypeCode.UInt64: ctx.LoadValue((long)(ulong)value); break; + default: throw new InvalidOperationException(); + } + } + private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, Compiler.CodeLabel handler, Compiler.CodeLabel @continue, object value, Compiler.Local local) + { + ctx.MarkLabel(handler); + WriteEnumValue(ctx, typeCode, value); + ctx.StoreValue(local); + ctx.Branch(@continue, false); // "continue" + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta new file mode 100644 index 00000000..b58d8661 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/EnumSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef6c6d630a8f5ca449eec10513147563 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs new file mode 100644 index 00000000..26c0452b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs @@ -0,0 +1,104 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class FieldDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => forType; + private readonly FieldInfo field; + private readonly Type forType; + public override bool RequiresOldValue => true; + public override bool ReturnsValue => false; + public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) : base(tail) + { + Helpers.DebugAssert(forType != null); + Helpers.DebugAssert(field != null); + this.forType = forType; + this.field = field; + } + + public override void Write(object value, ProtoWriter dest) + { + Helpers.DebugAssert(value != null); + value = field.GetValue(value); + if (value != null) Tail.Write(value, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value != null); + object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source); + if (newValue != null) field.SetValue(value, newValue); + return null; + } + + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadAddress(valueFrom, ExpectedType); + ctx.LoadValue(field); + ctx.WriteNullCheckedTail(field.FieldType, Tail, null); + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + if (Tail.RequiresOldValue) + { + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(field); + } + // value is either now on the stack or not needed + ctx.ReadNullCheckedTail(field.FieldType, Tail, null); + + // the field could be a backing field that needs to be raised back to + // the property if we're doing a full compile + MemberInfo member = field; + ctx.CheckAccessibility(ref member); + bool writeValue = member is FieldInfo; + + if (writeValue) + { + if (Tail.ReturnsValue) + { + using (Compiler.Local newVal = new Compiler.Local(ctx, field.FieldType)) + { + ctx.StoreValue(newVal); + if (Helpers.IsValueType(field.FieldType)) + { + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(newVal); + ctx.StoreValue(field); + } + else + { + Compiler.CodeLabel allDone = ctx.DefineLabel(); + ctx.LoadValue(newVal); + ctx.BranchIfFalse(allDone, true); // interpret null as "don't assign" + + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(newVal); + ctx.StoreValue(field); + + ctx.MarkLabel(allDone); + } + } + } + } + else + { + // can't use result + if (Tail.ReturnsValue) + { + ctx.DiscardValue(); + } + } + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta new file mode 100644 index 00000000..63065a7d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/FieldDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f7c1c3141cd2fad47b3112747b44314a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs new file mode 100644 index 00000000..27556d5b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class GuidSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(Guid); + + public GuidSerializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType { get { return expectedType; } } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteGuid((Guid)value, dest); + } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadGuid(source); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteGuid", valueFrom); + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadGuid", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta new file mode 100644 index 00000000..7eeb096c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/GuidSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 362fe2dd035b0cb4eaff2c7b7337fc66 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs new file mode 100644 index 00000000..59e8cc2e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs @@ -0,0 +1,64 @@ +#if !NO_RUNTIME +using System; + + +namespace ProtoBuf.Serializers +{ + interface IProtoSerializer + { + /// + /// The type that this serializer is intended to work for. + /// + Type ExpectedType { get; } + + /// + /// Perform the steps necessary to serialize this data. + /// + /// The value to be serialized. + /// The writer entity that is accumulating the output data. + void Write(object value, ProtoWriter dest); + + /// + /// Perform the steps necessary to deserialize this data. + /// + /// The current value, if appropriate. + /// The reader providing the input data. + /// The updated / replacement value. + object Read(object value, ProtoReader source); + + /// + /// Indicates whether a Read operation replaces the existing value, or + /// extends the value. If false, the "value" parameter to Read is + /// discarded, and should be passed in as null. + /// + bool RequiresOldValue { get; } + /// + /// Now all Read operations return a value (although most do); if false no + /// value should be expected. + /// + bool ReturnsValue { get; } + +#if FEAT_COMPILER + /// Emit the IL necessary to perform the given actions + /// to serialize this data. + /// + /// Details and utilities for the method being generated. + /// The source of the data to work against; + /// If the value is only needed once, then LoadValue is sufficient. If + /// the value is needed multiple times, then note that a "null" + /// means "the top of the stack", in which case you should create your + /// own copy - GetLocalWithValue. + void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom); + + /// + /// Emit the IL necessary to perform the given actions to deserialize this data. + /// + /// Details and utilities for the method being generated. + /// For nested values, the instance holding the values; note + /// that this is not always provided - a null means not supplied. Since this is always + /// a variable or argument, it is not necessary to consume this value. + void EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity); +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta new file mode 100644 index 00000000..40d402dd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6acc35442de99c94aade5d43c7992338 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs new file mode 100644 index 00000000..da1439bb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs @@ -0,0 +1,20 @@ +#if !NO_RUNTIME +using ProtoBuf.Meta; +namespace ProtoBuf.Serializers +{ + interface IProtoTypeSerializer : IProtoSerializer + { + bool HasCallbacks(TypeModel.CallbackType callbackType); + bool CanCreateInstance(); + object CreateInstance(ProtoReader source); + void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context); + +#if FEAT_COMPILER + void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType); +#endif +#if FEAT_COMPILER + void EmitCreateInstance(Compiler.CompilerContext ctx); +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta new file mode 100644 index 00000000..d4c96cf2 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/IProtoTypeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6974491708512ec41b7a5f29805e4c69 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs new file mode 100644 index 00000000..3ab2cb87 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs @@ -0,0 +1,10 @@ +#if !NO_RUNTIME + +namespace ProtoBuf.Serializers +{ + interface ISerializerProxy + { + IProtoSerializer Serializer { get; } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta new file mode 100644 index 00000000..aa3cdfa4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ISerializerProxy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f717dd1190cbe174587e3bff7dd3dd76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs new file mode 100644 index 00000000..918d1fd9 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs @@ -0,0 +1,304 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class ImmutableCollectionDecorator : ListDecorator + { + protected override bool RequireAdd { get { return false; } } + + static Type ResolveIReadOnlyCollection(Type declaredType, Type t) + { +#if COREFX || PROFILE259 + if (CheckIsIReadOnlyCollectionExactly(declaredType.GetTypeInfo())) return declaredType; + foreach (Type intImplBasic in declaredType.GetTypeInfo().ImplementedInterfaces) + { + TypeInfo intImpl = intImplBasic.GetTypeInfo(); + if (CheckIsIReadOnlyCollectionExactly(intImpl)) return intImplBasic; + } +#else + if (CheckIsIReadOnlyCollectionExactly(declaredType)) return declaredType; + foreach (Type intImpl in declaredType.GetInterfaces()) + { + if (CheckIsIReadOnlyCollectionExactly(intImpl)) return intImpl; + } +#endif + return null; + } + +#if WINRT || COREFX || PROFILE259 + static bool CheckIsIReadOnlyCollectionExactly(TypeInfo t) +#else + static bool CheckIsIReadOnlyCollectionExactly(Type t) +#endif + { + if (t != null && t.IsGenericType && t.Name.StartsWith("IReadOnlyCollection`")) + { +#if WINRT || COREFX || PROFILE259 + Type[] typeArgs = t.GenericTypeArguments; + if (typeArgs.Length != 1 && typeArgs[0].GetTypeInfo().Equals(t)) return false; +#else + Type[] typeArgs = t.GetGenericArguments(); + if (typeArgs.Length != 1 && typeArgs[0] != t) return false; +#endif + + return true; + } + return false; + } + + internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out PropertyInfo isEmpty, out PropertyInfo length, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish) + { + builderFactory = add = addRange = finish = null; + isEmpty = length = null; + if (model == null || declaredType == null) return false; +#if COREFX || PROFILE259 + TypeInfo declaredTypeInfo = declaredType.GetTypeInfo(); +#else + Type declaredTypeInfo = declaredType; +#endif + + // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection for some T + if (!declaredTypeInfo.IsGenericType) return false; + +#if COREFX || PROFILE259 + Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType; +#else + Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType; +#endif + switch (typeArgs.Length) + { + case 1: + effectiveType = typeArgs; + break; // fine + case 2: + Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>)); + if (kvp == null) return false; + kvp = kvp.MakeGenericType(typeArgs); + effectiveType = new Type[] { kvp }; + break; + default: + return false; // no clue! + } + + if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection found + + // and we want to use the builder API, so for generic Foo or IFoo we want to use Foo.CreateBuilder + string name = declaredType.Name; + int i = name.IndexOf('`'); + if (i <= 0) return false; + name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i); + + Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.Assembly); + // I hate special-cases... + if (outerType == null && name == "ImmutableSet") + { + outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.Assembly); + } + if (outerType == null) return false; + +#if PROFILE259 + foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods) +#else + foreach (MethodInfo method in outerType.GetMethods()) +#endif + { + if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0 + || method.GetGenericArguments().Length != typeArgs.Length) continue; + + builderFactory = method.MakeGenericMethod(typeArgs); + break; + } + Type voidType = model.MapType(typeof(void)); + if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false; + +#if COREFX + TypeInfo typeInfo = declaredType.GetTypeInfo(); +#else + Type typeInfo = declaredType; +#endif + isEmpty = Helpers.GetProperty(typeInfo, "IsDefaultOrEmpty", false); //struct based immutabletypes can have both a "default" and "empty" state + if (isEmpty == null) isEmpty = Helpers.GetProperty(typeInfo, "IsEmpty", false); + if (isEmpty == null) + { + //Fallback to checking length if a "IsEmpty" property is not found + length = Helpers.GetProperty(typeInfo, "Length", false); + if (length == null) length = Helpers.GetProperty(typeInfo, "Count", false); + + if (length == null) length = Helpers.GetProperty(ResolveIReadOnlyCollection(declaredType, effectiveType[0]), "Count", false); + + if (length == null) return false; + } + + add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType); + if (add == null) return false; + + finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes); + if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false; + + if (!(finish.ReturnType == declaredType || Helpers.IsAssignableFrom(declaredType, finish.ReturnType))) return false; + + addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType }); + if (addRange == null) + { + Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false); + if (enumerable != null) + { + addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) }); + } + } + + return true; + } + + private readonly MethodInfo builderFactory, add, addRange, finish; + private readonly PropertyInfo isEmpty, length; + internal ImmutableCollectionDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull, + MethodInfo builderFactory, PropertyInfo isEmpty, PropertyInfo length, MethodInfo add, MethodInfo addRange, MethodInfo finish) + : base(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull) + { + this.builderFactory = builderFactory; + this.isEmpty = isEmpty; + this.length = length; + this.add = add; + this.addRange = addRange; + this.finish = finish; + } + + public override object Read(object value, ProtoReader source) + { + object builderInstance = builderFactory.Invoke(null, null); + int field = source.FieldNumber; + object[] args = new object[1]; + if (AppendToCollection && value != null && (isEmpty != null ? !(bool)isEmpty.GetValue(value, null) : (int)length.GetValue(value, null) != 0)) + { + if (addRange != null) + { + args[0] = value; + addRange.Invoke(builderInstance, args); + } + else + { + foreach (object item in (ICollection)value) + { + args[0] = item; + add.Invoke(builderInstance, args); + } + } + } + + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + while (ProtoReader.HasSubValue(packedWireType, source)) + { + args[0] = Tail.Read(null, source); + add.Invoke(builderInstance, args); + } + ProtoReader.EndSubItem(token, source); + } + else + { + do + { + args[0] = Tail.Read(null, source); + add.Invoke(builderInstance, args); + } while (source.TryReadFieldHeader(field)); + } + + return finish.Invoke(builderInstance, null); + } + +#if FEAT_COMPILER + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local oldList = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null) + using (Compiler.Local builder = new Compiler.Local(ctx, builderFactory.ReturnType)) + { + ctx.EmitCall(builderFactory); + ctx.StoreValue(builder); + + if (AppendToCollection) + { + Compiler.CodeLabel done = ctx.DefineLabel(); + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.LoadValue(oldList); + ctx.BranchIfFalse(done, false); // old value null; nothing to add + } + + ctx.LoadAddress(oldList, oldList.Type); + if (isEmpty != null) + { + ctx.EmitCall(Helpers.GetGetMethod(isEmpty, false, false)); + ctx.BranchIfTrue(done, false); // old list is empty; nothing to add + } + else + { + ctx.EmitCall(Helpers.GetGetMethod(length, false, false)); + ctx.BranchIfFalse(done, false); // old list is empty; nothing to add + } + + Type voidType = ctx.MapType(typeof(void)); + if (addRange != null) + { + ctx.LoadValue(builder); + ctx.LoadValue(oldList); + ctx.EmitCall(addRange); + if (addRange.ReturnType != null && add.ReturnType != voidType) ctx.DiscardValue(); + } + else + { + // loop and call Add repeatedly + MethodInfo moveNext, current, getEnumerator = GetEnumeratorInfo(ctx.Model, out moveNext, out current); + Helpers.DebugAssert(moveNext != null); + Helpers.DebugAssert(current != null); + Helpers.DebugAssert(getEnumerator != null); + + Type enumeratorType = getEnumerator.ReturnType; + using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType)) + { + ctx.LoadAddress(oldList, ExpectedType); + ctx.EmitCall(getEnumerator); + ctx.StoreValue(iter); + using (ctx.Using(iter)) + { + Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel(); + ctx.Branch(next, false); + + ctx.MarkLabel(body); + ctx.LoadAddress(builder, builder.Type); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(current); + ctx.EmitCall(add); + if (add.ReturnType != null && add.ReturnType != voidType) ctx.DiscardValue(); + + ctx.MarkLabel(@next); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(moveNext); + ctx.BranchIfTrue(body, false); + } + } + } + + + ctx.MarkLabel(done); + } + + EmitReadList(ctx, builder, Tail, add, packedWireType, false); + + ctx.LoadAddress(builder, builder.Type); + ctx.EmitCall(finish); + if (ExpectedType != finish.ReturnType) + { + ctx.Cast(ExpectedType); + } + } + } +#endif + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta new file mode 100644 index 00000000..f8d90124 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ImmutableCollectionDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 00a3af58286d1674ca64bcf5fd9f0228 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs new file mode 100644 index 00000000..eac4eb42 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class Int16Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(short); + + public Int16Serializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadInt16(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt16((short)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt16", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadInt16", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta new file mode 100644 index 00000000..546159fe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int16Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e45229312d2a4fe45b519e513326b708 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs new file mode 100644 index 00000000..204880ef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs @@ -0,0 +1,42 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class Int32Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(int); + + public Int32Serializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadInt32(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt32((int)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt32", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadInt32", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta new file mode 100644 index 00000000..1be4c7e3 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int32Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a7c49bc45156f442bfe84fc7eef04b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs new file mode 100644 index 00000000..2791a1e5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs @@ -0,0 +1,41 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class Int64Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(long); + + public Int64Serializer(ProtoBuf.Meta.TypeModel model) { } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadInt64(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteInt64((long)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteInt64", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadInt64", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta new file mode 100644 index 00000000..8dbba5ea --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/Int64Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03f2770a306f45046b6e8eab757c9188 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ListDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ListDecorator.cs new file mode 100644 index 00000000..82bb128e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ListDecorator.cs @@ -0,0 +1,579 @@ +#if !NO_RUNTIME +using System; +using System.Collections; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + class ListDecorator : ProtoDecoratorBase + { + internal static bool CanPack(WireType wireType) + { + switch (wireType) + { + case WireType.Fixed32: + case WireType.Fixed64: + case WireType.SignedVariant: + case WireType.Variant: + return true; + default: + return false; + } + } + + private readonly byte options; + + private const byte OPTIONS_IsList = 1, + OPTIONS_SuppressIList = 2, + OPTIONS_WritePacked = 4, + OPTIONS_ReturnList = 8, + OPTIONS_OverwriteList = 16, + OPTIONS_SupportNull = 32; + + private readonly Type declaredType, concreteType; + + private readonly MethodInfo add; + + private readonly int fieldNumber; + + private bool IsList { get { return (options & OPTIONS_IsList) != 0; } } + private bool SuppressIList { get { return (options & OPTIONS_SuppressIList) != 0; } } + private bool WritePacked { get { return (options & OPTIONS_WritePacked) != 0; } } + private bool SupportNull { get { return (options & OPTIONS_SupportNull) != 0; } } + private bool ReturnList { get { return (options & OPTIONS_ReturnList) != 0; } } + protected readonly WireType packedWireType; + + internal static ListDecorator Create(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) + { + if (returnList && ImmutableCollectionDecorator.IdentifyImmutable(model, declaredType, + out MethodInfo builderFactory, + out PropertyInfo isEmpty, + out PropertyInfo length, + out MethodInfo add, + out MethodInfo addRange, + out MethodInfo finish)) + { + return new ImmutableCollectionDecorator( + model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull, + builderFactory, isEmpty, length, add, addRange, finish); + } + + return new ListDecorator(model, declaredType, concreteType, tail, fieldNumber, writePacked, packedWireType, returnList, overwriteList, supportNull); + } + + protected ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull) + : base(tail) + { + if (returnList) options |= OPTIONS_ReturnList; + if (overwriteList) options |= OPTIONS_OverwriteList; + if (supportNull) options |= OPTIONS_SupportNull; + if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); + if (!CanPack(packedWireType)) + { + if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding"); + packedWireType = WireType.None; + } + + this.fieldNumber = fieldNumber; + if (writePacked) options |= OPTIONS_WritePacked; + this.packedWireType = packedWireType; + if (declaredType == null) throw new ArgumentNullException("declaredType"); + if (declaredType.IsArray) throw new ArgumentException("Cannot treat arrays as lists", "declaredType"); + this.declaredType = declaredType; + this.concreteType = concreteType; + + // look for a public list.Add(typedObject) method + if (RequireAdd) + { + bool isList; + add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out isList); + if (isList) + { + options |= OPTIONS_IsList; + string fullName = declaredType.FullName; + if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[[")) + { // see http://stackoverflow.com/questions/6194639/entityset-is-there-a-sane-reason-that-ilist-add-doesnt-set-assigned + options |= OPTIONS_SuppressIList; + } + } + if (add == null) throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.FullName); + } + + } + protected virtual bool RequireAdd => true; + + public override Type ExpectedType => declaredType; + + public override bool RequiresOldValue => AppendToCollection; + + public override bool ReturnsValue => ReturnList; + + protected bool AppendToCollection + { + get { return (options & OPTIONS_OverwriteList) == 0; } + } + +#if FEAT_COMPILER + protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + /* This looks more complex than it is. Look at the non-compiled Read to + * see what it is trying to do, but note that it needs to cope with a + * few more scenarios. Note that it picks the **most specific** Add, + * unlike the runtime version that uses IList when possible. The core + * is just a "do {list.Add(readValue())} while {thereIsMore}" + * + * The complexity is due to: + * - value types vs reference types (boxing etc) + * - initialization if we need to pass in a value to the tail + * - handling whether or not the tail *returns* the value vs updates the input + */ + bool returnList = ReturnList; + + using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Compiler.Local(ctx, declaredType)) + using (Compiler.Local origlist = (returnList && AppendToCollection && !Helpers.IsValueType(ExpectedType)) ? new Compiler.Local(ctx, ExpectedType) : null) + { + if (!AppendToCollection) + { // always new + ctx.LoadNullRef(); + ctx.StoreValue(list); + } + else if (returnList && origlist != null) + { // need a copy + ctx.LoadValue(list); + ctx.StoreValue(origlist); + } + if (concreteType != null) + { + ctx.LoadValue(list); + Compiler.CodeLabel notNull = ctx.DefineLabel(); + ctx.BranchIfTrue(notNull, true); + ctx.EmitCtor(concreteType); + ctx.StoreValue(list); + ctx.MarkLabel(notNull); + } + + bool castListForAdd = !add.DeclaringType.IsAssignableFrom(declaredType); + EmitReadList(ctx, list, Tail, add, packedWireType, castListForAdd); + + if (returnList) + { + if (AppendToCollection && origlist != null) + { + // remember ^^^^ we had a spare copy of the list on the stack; now we'll compare + ctx.LoadValue(origlist); + ctx.LoadValue(list); // [orig] [new-value] + Compiler.CodeLabel sameList = ctx.DefineLabel(), allDone = ctx.DefineLabel(); + ctx.BranchIfEqual(sameList, true); + ctx.LoadValue(list); + ctx.Branch(allDone, true); + ctx.MarkLabel(sameList); + ctx.LoadNullRef(); + ctx.MarkLabel(allDone); + } + else + { + ctx.LoadValue(list); + } + } + } + } + + internal static void EmitReadList(ProtoBuf.Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, WireType packedWireType, bool castListForAdd) + { + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + Compiler.CodeLabel readPacked = packedWireType == WireType.None ? new Compiler.CodeLabel() : ctx.DefineLabel(); + if (packedWireType != WireType.None) + { + ctx.LoadReaderWriter(); + ctx.LoadValue(typeof(ProtoReader).GetProperty("WireType")); + ctx.LoadValue((int)WireType.String); + ctx.BranchIfEqual(readPacked, false); + } + ctx.LoadReaderWriter(); + ctx.LoadValue(typeof(ProtoReader).GetProperty("FieldNumber")); + ctx.StoreValue(fieldNumber); + + Compiler.CodeLabel @continue = ctx.DefineLabel(); + ctx.MarkLabel(@continue); + + EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); + + ctx.LoadReaderWriter(); + ctx.LoadValue(fieldNumber); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); + ctx.BranchIfTrue(@continue, false); + + if (packedWireType != WireType.None) + { + Compiler.CodeLabel allDone = ctx.DefineLabel(); + ctx.Branch(allDone, false); + ctx.MarkLabel(readPacked); + + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + + Compiler.CodeLabel testForData = ctx.DefineLabel(), noMoreData = ctx.DefineLabel(); + ctx.MarkLabel(testForData); + ctx.LoadValue((int)packedWireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("HasSubValue")); + ctx.BranchIfFalse(noMoreData, false); + + EmitReadAndAddItem(ctx, list, tail, add, castListForAdd); + ctx.Branch(testForData, false); + + ctx.MarkLabel(noMoreData); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.MarkLabel(allDone); + } + } + } + + private static void EmitReadAndAddItem(Compiler.CompilerContext ctx, Compiler.Local list, IProtoSerializer tail, MethodInfo add, bool castListForAdd) + { + ctx.LoadAddress(list, list.Type); // needs to be the reference in case the list is value-type (static-call) + if (castListForAdd) ctx.Cast(add.DeclaringType); + + Type itemType = tail.ExpectedType; + bool tailReturnsValue = tail.ReturnsValue; + if (tail.RequiresOldValue) + { + if (Helpers.IsValueType(itemType) || !tailReturnsValue) + { + // going to need a variable + using (Compiler.Local item = new Compiler.Local(ctx, itemType)) + { + if (Helpers.IsValueType(itemType)) + { // initialise the struct + ctx.LoadAddress(item, itemType); + ctx.EmitCtor(itemType); + } + else + { // assign null + ctx.LoadNullRef(); + ctx.StoreValue(item); + } + tail.EmitRead(ctx, item); + if (!tailReturnsValue) { ctx.LoadValue(item); } + } + } + else + { // no variable; pass the null on the stack and take the value *off* the stack + ctx.LoadNullRef(); + tail.EmitRead(ctx, null); + } + } + else + { + if (tailReturnsValue) + { // out only (on the stack); just emit it + tail.EmitRead(ctx, null); + } + else + { // doesn't take anything in nor return anything! WTF? + throw new InvalidOperationException(); + } + } + // our "Add" is chosen either to take the correct type, or to take "object"; + // we may need to box the value + + Type addParamType = add.GetParameters()[0].ParameterType; + if (addParamType != itemType) + { + if (addParamType == ctx.MapType(typeof(object))) + { + ctx.CastToObject(itemType); + } + else if (Helpers.GetUnderlyingType(addParamType) == itemType) + { // list is nullable + ConstructorInfo ctor = Helpers.GetConstructor(addParamType, new Type[] { itemType }, false); + ctx.EmitCtor(ctor); // the itemType on the stack is now a Nullable + } + else + { + throw new InvalidOperationException("Conflicting item/add type"); + } + } + ctx.EmitCall(add, list.Type); + if (add.ReturnType != ctx.MapType(typeof(void))) + { + ctx.DiscardValue(); + } + } +#endif + +#if COREFX + private static readonly TypeInfo ienumeratorType = typeof(IEnumerator).GetTypeInfo(), ienumerableType = typeof (IEnumerable).GetTypeInfo(); +#else + private static readonly System.Type ienumeratorType = typeof(IEnumerator), ienumerableType = typeof(IEnumerable); +#endif + protected MethodInfo GetEnumeratorInfo(TypeModel model, out MethodInfo moveNext, out MethodInfo current) + => GetEnumeratorInfo(model, ExpectedType, Tail.ExpectedType, out moveNext, out current); + internal static MethodInfo GetEnumeratorInfo(TypeModel model, Type expectedType, Type itemType, out MethodInfo moveNext, out MethodInfo current) + { + +#if COREFX + TypeInfo enumeratorType = null, iteratorType; +#else + Type enumeratorType = null, iteratorType; +#endif + + // try a custom enumerator + MethodInfo getEnumerator = Helpers.GetInstanceMethod(expectedType, "GetEnumerator", null); + + Type getReturnType = null; + if (getEnumerator != null) + { + getReturnType = getEnumerator.ReturnType; + iteratorType = getReturnType +#if COREFX || COREFX + .GetTypeInfo() +#endif + ; + moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext", null); + PropertyInfo prop = Helpers.GetProperty(iteratorType, "Current", false); + current = prop == null ? null : Helpers.GetGetMethod(prop, false, false); +#if PROFILE259 + if (moveNext == null && (model.MapType(ienumeratorType).GetTypeInfo().IsAssignableFrom(iteratorType.GetTypeInfo()))) +#else + if (moveNext == null && (model.MapType(ienumeratorType).IsAssignableFrom(iteratorType))) +#endif + { + moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext", null); + } + // fully typed + if (moveNext != null && moveNext.ReturnType == model.MapType(typeof(bool)) + && current != null && current.ReturnType == itemType) + { + return getEnumerator; + } + moveNext = current = getEnumerator = null; + } + + // try IEnumerable + Type tmp = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false); + + if (tmp != null) + { + tmp = tmp.MakeGenericType(itemType); + +#if COREFX + enumeratorType = tmp.GetTypeInfo(); +#else + enumeratorType = tmp; +#endif + } +; +#if PROFILE259 + if (enumeratorType != null && enumeratorType.GetTypeInfo().IsAssignableFrom(expectedType +#else + if (enumeratorType != null && enumeratorType.IsAssignableFrom(expectedType +#endif +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + )) + { + getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator"); + getReturnType = getEnumerator.ReturnType; + +#if COREFX + iteratorType = getReturnType.GetTypeInfo(); +#else + iteratorType = getReturnType; +#endif + + moveNext = Helpers.GetInstanceMethod(model.MapType(ienumeratorType), "MoveNext"); + current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false); + return getEnumerator; + } + // give up and fall-back to non-generic IEnumerable + enumeratorType = model.MapType(ienumerableType); + getEnumerator = Helpers.GetInstanceMethod(enumeratorType, "GetEnumerator"); + getReturnType = getEnumerator.ReturnType; + iteratorType = getReturnType +#if COREFX + .GetTypeInfo() +#endif + ; + moveNext = Helpers.GetInstanceMethod(iteratorType, "MoveNext"); + current = Helpers.GetGetMethod(Helpers.GetProperty(iteratorType, "Current", false), false, false); + return getEnumerator; + } +#if FEAT_COMPILER + protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + MethodInfo getEnumerator = GetEnumeratorInfo(ctx.Model, out MethodInfo moveNext, out MethodInfo current); + Helpers.DebugAssert(moveNext != null); + Helpers.DebugAssert(current != null); + Helpers.DebugAssert(getEnumerator != null); + Type enumeratorType = getEnumerator.ReturnType; + bool writePacked = WritePacked; + using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType)) + using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null) + { + if (writePacked) + { + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)WireType.String); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + + ctx.LoadValue(list); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + ctx.LoadValue(fieldNumber); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("SetPackedField")); + } + + ctx.LoadAddress(list, ExpectedType); + ctx.EmitCall(getEnumerator, ExpectedType); + ctx.StoreValue(iter); + using (ctx.Using(iter)) + { + Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel(); + ctx.Branch(next, false); + + ctx.MarkLabel(body); + + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(current, enumeratorType); + Type itemType = Tail.ExpectedType; + if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(itemType); + } + Tail.EmitWrite(ctx, null); + + ctx.MarkLabel(@next); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(moveNext, enumeratorType); + ctx.BranchIfTrue(body, false); + } + + if (writePacked) + { + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + } + } + } + } +#endif + + public override void Write(object value, ProtoWriter dest) + { + SubItemToken token; + bool writePacked = WritePacked; + bool fixedSizePacked = writePacked & CanUsePackedPrefix(value) && value is ICollection; + if (writePacked) + { + ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest); + if (fixedSizePacked) + { + ProtoWriter.WritePackedPrefix(((ICollection)value).Count, packedWireType, dest); + token = default(SubItemToken); + } + else + { + token = ProtoWriter.StartSubItem(value, dest); + } + ProtoWriter.SetPackedField(fieldNumber, dest); + } + else + { + token = new SubItemToken(); // default + } + bool checkForNull = !SupportNull; + foreach (object subItem in (IEnumerable)value) + { + if (checkForNull && subItem == null) { throw new NullReferenceException(); } + Tail.Write(subItem, dest); + } + if (writePacked) + { + if (fixedSizePacked) + { + ProtoWriter.ClearPackedField(fieldNumber, dest); + } + else + { + ProtoWriter.EndSubItem(token, dest); + } + } + } + + private bool CanUsePackedPrefix(object obj) => + ArrayDecorator.CanUsePackedPrefix(packedWireType, Tail.ExpectedType); + + public override object Read(object value, ProtoReader source) + { + try + { + int field = source.FieldNumber; + object origValue = value; + if (value == null) value = Activator.CreateInstance(concreteType); + bool isList = IsList && !SuppressIList; + if (packedWireType != WireType.None && source.WireType == WireType.String) + { + SubItemToken token = ProtoReader.StartSubItem(source); + if (isList) + { + IList list = (IList)value; + while (ProtoReader.HasSubValue(packedWireType, source)) + { + list.Add(Tail.Read(null, source)); + } + } + else + { + object[] args = new object[1]; + while (ProtoReader.HasSubValue(packedWireType, source)) + { + args[0] = Tail.Read(null, source); + add.Invoke(value, args); + } + } + ProtoReader.EndSubItem(token, source); + } + else + { + if (isList) + { + IList list = (IList)value; + do + { + list.Add(Tail.Read(null, source)); + } while (source.TryReadFieldHeader(field)); + } + else + { + object[] args = new object[1]; + do + { + args[0] = Tail.Read(null, source); + add.Invoke(value, args); + } while (source.TryReadFieldHeader(field)); + } + } + return origValue == value ? null : value; + } + catch (TargetInvocationException tie) + { + if (tie.InnerException != null) throw tie.InnerException; + throw; + } + } + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta new file mode 100644 index 00000000..a5980a26 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ListDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb7a73aa78c887c478b0af6d506337d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MapDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MapDecorator.cs new file mode 100644 index 00000000..033cf26a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MapDecorator.cs @@ -0,0 +1,298 @@ +using ProtoBuf.Meta; +using System; +#if FEAT_COMPILER +using ProtoBuf.Compiler; +#endif +using System.Collections.Generic; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + class MapDecorator : ProtoDecoratorBase where TDictionary : class, IDictionary + { + private readonly Type concreteType; + private readonly IProtoSerializer keyTail; + private readonly int fieldNumber; + private readonly WireType wireType; + + internal MapDecorator(TypeModel model, Type concreteType, IProtoSerializer keyTail, IProtoSerializer valueTail, + int fieldNumber, WireType wireType, WireType keyWireType, WireType valueWireType, bool overwriteList) + : base(DefaultValue == null + ? (IProtoSerializer)new TagDecorator(2, valueWireType, false, valueTail) + : (IProtoSerializer)new DefaultValueDecorator(model, DefaultValue, new TagDecorator(2, valueWireType, false, valueTail))) + { + this.wireType = wireType; + this.keyTail = new DefaultValueDecorator(model, DefaultKey, new TagDecorator(1, keyWireType, false, keyTail)); + this.fieldNumber = fieldNumber; + this.concreteType = concreteType ?? typeof(TDictionary); + + if (keyTail.RequiresOldValue) throw new InvalidOperationException("Key tail should not require the old value"); + if (!keyTail.ReturnsValue) throw new InvalidOperationException("Key tail should return a value"); + if (!valueTail.ReturnsValue) throw new InvalidOperationException("Value tail should return a value"); + + AppendToCollection = !overwriteList; + } + + private static readonly MethodInfo indexerSet = GetIndexerSetter(); + + private static MethodInfo GetIndexerSetter() + { +#if PROFILE259 + foreach(var prop in typeof(TDictionary).GetRuntimeProperties()) +#else + foreach (var prop in typeof(TDictionary).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) +#endif + { + if (prop.Name != "Item") continue; + if (prop.PropertyType != typeof(TValue)) continue; + + var args = prop.GetIndexParameters(); + if (args == null || args.Length != 1) continue; + + if (args[0].ParameterType != typeof(TKey)) continue; +#if PROFILE259 + var method = prop.SetMethod; +#else + var method = prop.GetSetMethod(true); +#endif + if (method != null) + { + return method; + } + } + throw new InvalidOperationException("Unable to resolve indexer for map"); + } + + private static readonly TKey DefaultKey = (typeof(TKey) == typeof(string)) ? (TKey)(object)"" : default(TKey); + private static readonly TValue DefaultValue = (typeof(TValue) == typeof(string)) ? (TValue)(object)"" : default(TValue); + public override Type ExpectedType => typeof(TDictionary); + + public override bool ReturnsValue => true; + + public override bool RequiresOldValue => AppendToCollection; + + private bool AppendToCollection { get; } + + public override object Read(object untyped, ProtoReader source) + { + TDictionary typed = AppendToCollection ? ((TDictionary)untyped) : null; + if (typed == null) typed = (TDictionary)Activator.CreateInstance(concreteType); + + do + { + var key = DefaultKey; + var value = DefaultValue; + SubItemToken token = ProtoReader.StartSubItem(source); + int field; + while ((field = source.ReadFieldHeader()) > 0) + { + switch (field) + { + case 1: + key = (TKey)keyTail.Read(null, source); + break; + case 2: + value = (TValue)Tail.Read(Tail.RequiresOldValue ? (object)value : null, source); + break; + default: + source.SkipField(); + break; + } + } + + ProtoReader.EndSubItem(token, source); + typed[key] = value; + } while (source.TryReadFieldHeader(fieldNumber)); + + return typed; + } + + public override void Write(object untyped, ProtoWriter dest) + { + foreach (var pair in (TDictionary)untyped) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); + var token = ProtoWriter.StartSubItem(null, dest); + if (pair.Key != null) keyTail.Write(pair.Key, dest); + if (pair.Value != null) Tail.Write(pair.Value, dest); + ProtoWriter.EndSubItem(token, dest); + } + } + +#if FEAT_COMPILER + protected override void EmitWrite(CompilerContext ctx, Local valueFrom) + { + Type itemType = typeof(KeyValuePair); + MethodInfo moveNext, current, getEnumerator = ListDecorator.GetEnumeratorInfo(ctx.Model, + ExpectedType, itemType, out moveNext, out current); + Type enumeratorType = getEnumerator.ReturnType; + + MethodInfo key = itemType.GetProperty(nameof(KeyValuePair.Key)).GetGetMethod(), + @value = itemType.GetProperty(nameof(KeyValuePair.Value)).GetGetMethod(); + + using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType)) + using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken))) + using (Compiler.Local kvp = new Compiler.Local(ctx, itemType)) + { + ctx.LoadAddress(list, ExpectedType); + ctx.EmitCall(getEnumerator, ExpectedType); + ctx.StoreValue(iter); + using (ctx.Using(iter)) + { + Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel(); + ctx.Branch(next, false); + + ctx.MarkLabel(body); + + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(current, enumeratorType); + + if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(itemType); + } + ctx.StoreValue(kvp); + + ctx.LoadValue(fieldNumber); + ctx.LoadValue((int)wireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + + ctx.LoadNullRef(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + ctx.LoadAddress(kvp, itemType); + ctx.EmitCall(key, itemType); + ctx.WriteNullCheckedTail(typeof(TKey), keyTail, null); + + ctx.LoadAddress(kvp, itemType); + ctx.EmitCall(value, itemType); + ctx.WriteNullCheckedTail(typeof(TValue), Tail, null); + + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + + ctx.MarkLabel(@next); + ctx.LoadAddress(iter, enumeratorType); + ctx.EmitCall(moveNext, enumeratorType); + ctx.BranchIfTrue(body, false); + } + } + } + protected override void EmitRead(CompilerContext ctx, Local valueFrom) + { + using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) + : new Compiler.Local(ctx, typeof(TDictionary))) + using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken))) + using (Compiler.Local key = new Compiler.Local(ctx, typeof(TKey))) + using (Compiler.Local @value = new Compiler.Local(ctx, typeof(TValue))) + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + if (!AppendToCollection) + { // always new + ctx.LoadNullRef(); + ctx.StoreValue(list); + } + if (concreteType != null) + { + ctx.LoadValue(list); + Compiler.CodeLabel notNull = ctx.DefineLabel(); + ctx.BranchIfTrue(notNull, true); + ctx.EmitCtor(concreteType); + ctx.StoreValue(list); + ctx.MarkLabel(notNull); + } + + var redoFromStart = ctx.DefineLabel(); + ctx.MarkLabel(redoFromStart); + + // key = default(TKey); value = default(TValue); + if (typeof(TKey) == typeof(string)) + { + ctx.LoadValue(""); + ctx.StoreValue(key); + } + else + { + ctx.InitLocal(typeof(TKey), key); + } + if (typeof(TValue) == typeof(string)) + { + ctx.LoadValue(""); + ctx.StoreValue(value); + } + else + { + ctx.InitLocal(typeof(TValue), @value); + } + + // token = ProtoReader.StartSubItem(reader); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel(); + // while ... + ctx.Branch(@continue, false); + + // switch(fieldNumber) + ctx.MarkLabel(processField); + ctx.LoadValue(fieldNumber); + CodeLabel @default = ctx.DefineLabel(), one = ctx.DefineLabel(), two = ctx.DefineLabel(); + ctx.Switch(new[] { @default, one, two }); // zero based, hence explicit 0 + + // case 0: default: reader.SkipField(); + ctx.MarkLabel(@default); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.Branch(@continue, false); + + // case 1: key = ... + ctx.MarkLabel(one); + keyTail.EmitRead(ctx, null); + ctx.StoreValue(key); + ctx.Branch(@continue, false); + + // case 2: value = ... + ctx.MarkLabel(two); + Tail.EmitRead(ctx, Tail.RequiresOldValue ? @value : null); + ctx.StoreValue(value); + + // (fieldNumber = reader.ReadFieldHeader()) > 0 + ctx.MarkLabel(@continue); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(fieldNumber); + ctx.LoadValue(0); + ctx.BranchIfGreater(processField, false); + + // ProtoReader.EndSubItem(token, reader); + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + + // list[key] = value; + ctx.LoadAddress(list, ExpectedType); + ctx.LoadValue(key); + ctx.LoadValue(@value); + ctx.EmitCall(indexerSet); + + // while reader.TryReadFieldReader(fieldNumber) + ctx.LoadReaderWriter(); + ctx.LoadValue(this.fieldNumber); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("TryReadFieldHeader")); + ctx.BranchIfTrue(redoFromStart, false); + + if (ReturnsValue) + { + ctx.LoadValue(list); + } + } + } +#endif + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta new file mode 100644 index 00000000..51c45254 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MapDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 522b5c8a0fa5be14591bc9cbe3b194d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs new file mode 100644 index 00000000..3ee80a55 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs @@ -0,0 +1,76 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class MemberSpecifiedDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => Tail.ExpectedType; + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private readonly MethodInfo getSpecified, setSpecified; + public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IProtoSerializer tail) + : base(tail) + { + if (getSpecified == null && setSpecified == null) throw new InvalidOperationException(); + this.getSpecified = getSpecified; + this.setSpecified = setSpecified; + } + + public override void Write(object value, ProtoWriter dest) + { + if (getSpecified == null || (bool)getSpecified.Invoke(value, null)) + { + Tail.Write(value, dest); + } + } + + public override object Read(object value, ProtoReader source) + { + object result = Tail.Read(value, source); + if (setSpecified != null) setSpecified.Invoke(value, new object[] { true }); + return result; + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (getSpecified == null) + { + Tail.EmitWrite(ctx, valueFrom); + return; + } + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + ctx.LoadAddress(loc, ExpectedType); + ctx.EmitCall(getSpecified); + Compiler.CodeLabel done = ctx.DefineLabel(); + ctx.BranchIfFalse(done, false); + Tail.EmitWrite(ctx, loc); + ctx.MarkLabel(done); + } + + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (setSpecified == null) + { + Tail.EmitRead(ctx, valueFrom); + return; + } + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + Tail.EmitRead(ctx, loc); + ctx.LoadAddress(loc, ExpectedType); + ctx.LoadValue(1); // true + ctx.EmitCall(setSpecified); + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta new file mode 100644 index 00000000..f2d61875 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/MemberSpecifiedDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58836f822e85e2447817d187f3bcd5de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs new file mode 100644 index 00000000..c3d685b8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs @@ -0,0 +1,64 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class NetObjectSerializer : IProtoSerializer + { + private readonly int key; + private readonly Type type; + + private readonly BclHelpers.NetObjectOptions options; + + public NetObjectSerializer(TypeModel model, Type type, int key, BclHelpers.NetObjectOptions options) + { + bool dynamicType = (options & BclHelpers.NetObjectOptions.DynamicType) != 0; + this.key = dynamicType ? -1 : key; + this.type = dynamicType ? model.MapType(typeof(object)) : type; + this.options = options; + } + + public Type ExpectedType => type; + + public bool ReturnsValue => true; + + public bool RequiresOldValue => true; + + public object Read(object value, ProtoReader source) + { + return BclHelpers.ReadNetObject(value, source, key, type == typeof(object) ? null : type, options); + } + + public void Write(object value, ProtoWriter dest) + { + BclHelpers.WriteNetObject(value, dest, key, options); + } + +#if FEAT_COMPILER + public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.CastToObject(type); + ctx.LoadReaderWriter(); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + if (type == ctx.MapType(typeof(object))) ctx.LoadNullRef(); + else ctx.LoadValue(type); + ctx.LoadValue((int)options); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("ReadNetObject")); + ctx.CastFromObject(type); + } + public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.CastToObject(type); + ctx.LoadReaderWriter(); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); + ctx.LoadValue((int)options); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("WriteNetObject")); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta new file mode 100644 index 00000000..f53dfadc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NetObjectSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd6edd815f76150449f39f7571679912 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NullDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NullDecorator.cs new file mode 100644 index 00000000..52db14ce --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NullDecorator.cs @@ -0,0 +1,167 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class NullDecorator : ProtoDecoratorBase + { + private readonly Type expectedType; + public const int Tag = 1; + public NullDecorator(TypeModel model, IProtoSerializer tail) : base(tail) + { + if (!tail.ReturnsValue) + throw new NotSupportedException("NullDecorator only supports implementations that return values"); + + Type tailType = tail.ExpectedType; + if (Helpers.IsValueType(tailType)) + { + expectedType = model.MapType(typeof(Nullable<>)).MakeGenericType(tailType); + } + else + { + expectedType = tailType; + } + } + + public override Type ExpectedType => expectedType; + + public override bool ReturnsValue => true; + + public override bool RequiresOldValue => true; + +#if FEAT_COMPILER + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local oldValue = ctx.GetLocalWithValue(expectedType, valueFrom)) + using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) + using (Compiler.Local field = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + Compiler.CodeLabel next = ctx.DefineLabel(), processField = ctx.DefineLabel(), end = ctx.DefineLabel(); + + ctx.MarkLabel(next); + + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(field); + ctx.LoadValue(Tag); // = 1 - process + ctx.BranchIfEqual(processField, true); + ctx.LoadValue(field); + ctx.LoadValue(1); // < 1 - exit + ctx.BranchIfLess(end, false); + + // default: skip + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + ctx.Branch(next, true); + + // process + ctx.MarkLabel(processField); + if (Tail.RequiresOldValue) + { + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(oldValue, expectedType); + ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + else + { + ctx.LoadValue(oldValue); + } + } + Tail.EmitRead(ctx, null); + // note we demanded always returns a value + if (Helpers.IsValueType(expectedType)) + { + ctx.EmitCtor(expectedType, Tail.ExpectedType); // re-nullable it + } + ctx.StoreValue(oldValue); + ctx.Branch(next, false); + + // outro + ctx.MarkLabel(end); + + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); + ctx.LoadValue(oldValue); // load the old value + } + } + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local valOrNull = ctx.GetLocalWithValue(expectedType, valueFrom)) + using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) + { + ctx.LoadNullRef(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); + ctx.StoreValue(token); + + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(valOrNull, expectedType); + ctx.LoadValue(expectedType.GetProperty("HasValue")); + } + else + { + ctx.LoadValue(valOrNull); + } + Compiler.CodeLabel @end = ctx.DefineLabel(); + ctx.BranchIfFalse(@end, false); + if (Helpers.IsValueType(expectedType)) + { + ctx.LoadAddress(valOrNull, expectedType); + ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); + } + else + { + ctx.LoadValue(valOrNull); + } + Tail.EmitWrite(ctx, null); + + ctx.MarkLabel(@end); + + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); + } + } +#endif + + public override object Read(object value, ProtoReader source) + { + SubItemToken tok = ProtoReader.StartSubItem(source); + int field; + while ((field = source.ReadFieldHeader()) > 0) + { + if (field == Tag) + { + value = Tail.Read(value, source); + } + else + { + source.SkipField(); + } + } + ProtoReader.EndSubItem(tok, source); + return value; + } + + public override void Write(object value, ProtoWriter dest) + { + SubItemToken token = ProtoWriter.StartSubItem(null, dest); + if (value != null) + { + Tail.Write(value, dest); + } + ProtoWriter.EndSubItem(token, dest); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta new file mode 100644 index 00000000..4fb2a35c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/NullDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4728d79a9a96bde4097e4c599266a6e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs new file mode 100644 index 00000000..9a4bb07c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs @@ -0,0 +1,111 @@ +#if !NO_RUNTIME +using System; +using System.Net; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class ParseableSerializer : IProtoSerializer + { + private readonly MethodInfo parse; + public static ParseableSerializer TryCreate(Type type, TypeModel model) + { + if (type == null) throw new ArgumentNullException("type"); +#if PORTABLE || COREFX || PROFILE259 + MethodInfo method = null; + +#if COREFX || PROFILE259 + foreach (MethodInfo tmp in type.GetTypeInfo().GetDeclaredMethods("Parse")) +#else + foreach (MethodInfo tmp in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) +#endif + { + ParameterInfo[] p; + if (tmp.Name == "Parse" && tmp.IsPublic && tmp.IsStatic && tmp.DeclaringType == type && (p = tmp.GetParameters()) != null && p.Length == 1 && p[0].ParameterType == typeof(string)) + { + method = tmp; + break; + } + } +#else + MethodInfo method = type.GetMethod("Parse", + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, + null, new Type[] { model.MapType(typeof(string)) }, null); +#endif + if (method != null && method.ReturnType == type) + { + if (Helpers.IsValueType(type)) + { + MethodInfo toString = GetCustomToString(type); + if (toString == null || toString.ReturnType != model.MapType(typeof(string))) return null; // need custom ToString, fools + } + return new ParseableSerializer(method); + } + return null; + } + private static MethodInfo GetCustomToString(Type type) + { +#if PORTABLE || COREFX || PROFILE259 + MethodInfo method = Helpers.GetInstanceMethod(type, "ToString", Helpers.EmptyTypes); + if (method == null || !method.IsPublic || method.IsStatic || method.DeclaringType != type) return null; + return method; +#else + + return type.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, + null, Helpers.EmptyTypes, null); +#endif + } + + private ParseableSerializer(MethodInfo parse) + { + this.parse = parse; + } + + public Type ExpectedType => parse.DeclaringType; + + bool IProtoSerializer.RequiresOldValue { get { return false; } } + bool IProtoSerializer.ReturnsValue { get { return true; } } + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return parse.Invoke(null, new object[] { source.ReadString() }); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteString(value.ToString(), dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Type type = ExpectedType; + if (Helpers.IsValueType(type)) + { // note that for structs, we've already asserted that a custom ToString + // exists; no need to handle the box/callvirt scenario + + // force it to a variable if needed, so we can take the address + using (Compiler.Local loc = ctx.GetLocalWithValue(type, valueFrom)) + { + ctx.LoadAddress(loc, type); + ctx.EmitCall(GetCustomToString(type)); + } + } + else + { + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("ToString")); + } + ctx.EmitBasicWrite("WriteString", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadString", ctx.MapType(typeof(string))); + ctx.EmitCall(parse); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta new file mode 100644 index 00000000..9ee5ec19 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ParseableSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 562e4dd519901854fba22d511f594b82 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs new file mode 100644 index 00000000..8b0a0147 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs @@ -0,0 +1,167 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class PropertyDecorator : ProtoDecoratorBase + { + public override Type ExpectedType => forType; + private readonly PropertyInfo property; + private readonly Type forType; + public override bool RequiresOldValue => true; + public override bool ReturnsValue => false; + private readonly bool readOptionsWriteValue; + private readonly MethodInfo shadowSetter; + + public PropertyDecorator(TypeModel model, Type forType, PropertyInfo property, IProtoSerializer tail) : base(tail) + { + Helpers.DebugAssert(forType != null); + Helpers.DebugAssert(property != null); + this.forType = forType; + this.property = property; + SanityCheck(model, property, tail, out readOptionsWriteValue, true, true); + shadowSetter = GetShadowSetter(model, property); + } + + private static void SanityCheck(TypeModel model, PropertyInfo property, IProtoSerializer tail, out bool writeValue, bool nonPublic, bool allowInternal) + { + if (property == null) throw new ArgumentNullException("property"); + + writeValue = tail.ReturnsValue && (GetShadowSetter(model, property) != null || (property.CanWrite && Helpers.GetSetMethod(property, nonPublic, allowInternal) != null)); + if (!property.CanRead || Helpers.GetGetMethod(property, nonPublic, allowInternal) == null) + { + throw new InvalidOperationException("Cannot serialize property without a get accessor"); + } + if (!writeValue && (!tail.RequiresOldValue || Helpers.IsValueType(tail.ExpectedType))) + { // so we can't save the value, and the tail doesn't use it either... not helpful + // or: can't write the value, so the struct value will be lost + throw new InvalidOperationException("Cannot apply changes to property " + property.DeclaringType.FullName + "." + property.Name); + } + } + static MethodInfo GetShadowSetter(TypeModel model, PropertyInfo property) + { +#if COREFX + MethodInfo method = Helpers.GetInstanceMethod(property.DeclaringType.GetTypeInfo(), "Set" + property.Name, new Type[] { property.PropertyType }); +#else + +#if PROFILE259 + Type reflectedType = property.DeclaringType; +#else + Type reflectedType = property.ReflectedType; +#endif + MethodInfo method = Helpers.GetInstanceMethod(reflectedType, "Set" + property.Name, new Type[] { property.PropertyType }); +#endif + if (method == null || !method.IsPublic || method.ReturnType != model.MapType(typeof(void))) return null; + return method; + } + + public override void Write(object value, ProtoWriter dest) + { + Helpers.DebugAssert(value != null); + value = property.GetValue(value, null); + if (value != null) Tail.Write(value, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value != null); + + object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null; + object newVal = Tail.Read(oldVal, source); + if (readOptionsWriteValue && newVal != null) // if the tail returns a null, intepret that as *no assign* + { + if (shadowSetter == null) + { + property.SetValue(value, newVal, null); + } + else + { + shadowSetter.Invoke(value, new object[] { newVal }); + } + } + return null; + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadAddress(valueFrom, ExpectedType); + ctx.LoadValue(property); + ctx.WriteNullCheckedTail(property.PropertyType, Tail, null); + } + + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + SanityCheck(ctx.Model, property, Tail, out bool writeValue, ctx.NonPublic, ctx.AllowInternal(property)); + if (Helpers.IsValueType(ExpectedType) && valueFrom == null) + { + throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost"); + } + + using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) + { + if (Tail.RequiresOldValue) + { + ctx.LoadAddress(loc, ExpectedType); // stack is: old-addr + ctx.LoadValue(property); // stack is: old-value + } + Type propertyType = property.PropertyType; + ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [new-value] + + if (writeValue) + { + using (Compiler.Local newVal = new Compiler.Local(ctx, property.PropertyType)) + { + ctx.StoreValue(newVal); // stack is empty + + Compiler.CodeLabel allDone = new Compiler.CodeLabel(); // <=== default structs + if (!Helpers.IsValueType(propertyType)) + { // if the tail returns a null, intepret that as *no assign* + allDone = ctx.DefineLabel(); + ctx.LoadValue(newVal); // stack is: new-value + ctx.BranchIfFalse(@allDone, true); // stack is empty + } + // assign the value + ctx.LoadAddress(loc, ExpectedType); // parent-addr + ctx.LoadValue(newVal); // parent-obj|new-value + if (shadowSetter == null) + { + ctx.StoreValue(property); // empty + } + else + { + ctx.EmitCall(shadowSetter); // empty + } + if (!Helpers.IsValueType(propertyType)) + { + ctx.MarkLabel(allDone); + } + } + + } + else + { // don't want return value; drop it if anything there + // stack is [new-value] + if (Tail.ReturnsValue) { ctx.DiscardValue(); } + } + } + } +#endif + + internal static bool CanWrite(TypeModel model, MemberInfo member) + { + if (member == null) throw new ArgumentNullException(nameof(member)); + + if (member is PropertyInfo prop) + { + return prop.CanWrite || GetShadowSetter(model, prop) != null; + } + + return member is FieldInfo; // fields are always writeable; anything else: JUST SAY NO! + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta new file mode 100644 index 00000000..5aca94d0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/PropertyDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b21fd2b2435fed4da28bd193e2ce80d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs new file mode 100644 index 00000000..e7f2b34b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs @@ -0,0 +1,24 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + abstract class ProtoDecoratorBase : IProtoSerializer + { + public abstract Type ExpectedType { get; } + protected readonly IProtoSerializer Tail; + protected ProtoDecoratorBase(IProtoSerializer tail) { this.Tail = tail; } + public abstract bool ReturnsValue { get; } + public abstract bool RequiresOldValue { get; } + public abstract void Write(object value, ProtoWriter dest); + public abstract object Read(object value, ProtoReader source); + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitWrite(ctx, valueFrom); } + protected abstract void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom); + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitRead(ctx, valueFrom); } + protected abstract void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom); +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta new file mode 100644 index 00000000..92acdfcf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ProtoDecoratorBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e9afbb9465ade140ab0fcd217ea0b66 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs new file mode 100644 index 00000000..44edef07 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs @@ -0,0 +1,90 @@ +#if !NO_RUNTIME +#if PORTABLE +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + /// + /// Manipulates with uris via reflection rather than strongly typed objects. + /// This is because in PCLs, the Uri type may not match (WinRT uses Internal/Uri, .Net uses System/Uri) + /// + sealed class ReflectedUriDecorator : ProtoDecoratorBase + { + private readonly Type expectedType; + + private readonly PropertyInfo absoluteUriProperty; + + private readonly ConstructorInfo typeConstructor; + + public ReflectedUriDecorator(Type type, ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail) + { + expectedType = type; + +#if PROFILE259 + absoluteUriProperty = expectedType.GetRuntimeProperty("AbsoluteUri"); + IEnumerable constructors = expectedType.GetTypeInfo().DeclaredConstructors; + typeConstructor = null; + foreach(ConstructorInfo constructor in constructors) + { + ParameterInfo[] parameters = constructor.GetParameters(); + ParameterInfo parameterFirst = parameters.FirstOrDefault(); + Type stringType = typeof(string); + if (parameterFirst != null && + parameterFirst.ParameterType == stringType) + { + typeConstructor = constructor; + break; + } + } +#else + absoluteUriProperty = expectedType.GetProperty("AbsoluteUri"); + typeConstructor = expectedType.GetConstructor(new Type[] { typeof(string) }); +#endif + } + public override Type ExpectedType { get { return expectedType; } } + public override bool RequiresOldValue { get { return false; } } + public override bool ReturnsValue { get { return true; } } + + public override void Write(object value, ProtoWriter dest) + { + Tail.Write(absoluteUriProperty.GetValue(value, null), dest); + } + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // not expecting incoming + string s = (string)Tail.Read(null, source); + + return s.Length == 0 ? null : typeConstructor.Invoke(new object[] { s }); + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.LoadValue(absoluteUriProperty); + Tail.EmitWrite(ctx, null); + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + ctx.CopyValue(); + Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel(); + ctx.LoadValue(typeof(string).GetProperty("Length")); + ctx.BranchIfTrue(@nonEmpty, true); + ctx.DiscardValue(); + ctx.LoadNullRef(); + ctx.Branch(@end, true); + ctx.MarkLabel(@nonEmpty); + ctx.EmitCtor(expectedType, ctx.MapType(typeof(string))); + ctx.MarkLabel(@end); + + } +#endif + } +} +#endif +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta new file mode 100644 index 00000000..2441cdf0 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/ReflectedUriDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6cf63470b1970d84ead637b9ee2bface +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs new file mode 100644 index 00000000..81d233e1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs @@ -0,0 +1,45 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class SByteSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(sbyte); + + public SByteSerializer(ProtoBuf.Meta.TypeModel model) + { + + } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadSByte(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteSByte((sbyte)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteSByte", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadSByte", ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta new file mode 100644 index 00000000..7d71fefa --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SByteSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09de0f3e56d4834428cb8ba75929d216 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs new file mode 100644 index 00000000..c5ade137 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs @@ -0,0 +1,45 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class SingleSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(float); + + public Type ExpectedType { get { return expectedType; } } + + public SingleSerializer(TypeModel model) + { + } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadSingle(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteSingle((float)value, dest); + } + + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteSingle", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadSingle", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta new file mode 100644 index 00000000..ee64e5ac --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SingleSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b89c111cae2d81469987d208a41af4b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/StringSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/StringSerializer.cs new file mode 100644 index 00000000..399b4bb4 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/StringSerializer.cs @@ -0,0 +1,41 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class StringSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(string); + + public StringSerializer(ProtoBuf.Meta.TypeModel model) + { + } + + public Type ExpectedType => expectedType; + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteString((string)value, dest); + } + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadString(); + } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteString", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadString", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta new file mode 100644 index 00000000..697d8c29 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/StringSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80c8f3efc5f697845b352b56780105ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs new file mode 100644 index 00000000..58015aad --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs @@ -0,0 +1,138 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; + +#if FEAT_COMPILER +using System.Reflection.Emit; +#endif + +namespace ProtoBuf.Serializers +{ + sealed class SubItemSerializer : IProtoTypeSerializer + { + bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) + { + return ((IProtoTypeSerializer)proxy.Serializer).HasCallbacks(callbackType); + } + + bool IProtoTypeSerializer.CanCreateInstance() + { + return ((IProtoTypeSerializer)proxy.Serializer).CanCreateInstance(); + } + +#if FEAT_COMPILER + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + ((IProtoTypeSerializer)proxy.Serializer).EmitCallback(ctx, valueFrom, callbackType); + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) + { + ((IProtoTypeSerializer)proxy.Serializer).EmitCreateInstance(ctx); + } +#endif + + void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + ((IProtoTypeSerializer)proxy.Serializer).Callback(value, callbackType, context); + } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return ((IProtoTypeSerializer)proxy.Serializer).CreateInstance(source); + } + + private readonly int key; + private readonly Type type; + private readonly ISerializerProxy proxy; + private readonly bool recursionCheck; + public SubItemSerializer(Type type, int key, ISerializerProxy proxy, bool recursionCheck) + { + this.type = type ?? throw new ArgumentNullException(nameof(type)); + this.proxy = proxy ?? throw new ArgumentNullException(nameof(proxy)); + this.key = key; + this.recursionCheck = recursionCheck; + } + + Type IProtoSerializer.ExpectedType => type; + + bool IProtoSerializer.RequiresOldValue => true; + + bool IProtoSerializer.ReturnsValue => true; + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + if (recursionCheck) + { + ProtoWriter.WriteObject(value, key, dest); + } + else + { + ProtoWriter.WriteRecursionSafeObject(value, key, dest); + } + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + return ProtoReader.ReadObject(value, key, source); + } + +#if FEAT_COMPILER + bool EmitDedicatedMethod(Compiler.CompilerContext ctx, Compiler.Local valueFrom, bool read) + { + MethodBuilder method = ctx.GetDedicatedMethod(key, read); + if (method == null) return false; + + using (Compiler.Local token = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) + { + Type rwType = ctx.MapType(read ? typeof(ProtoReader) : typeof(ProtoWriter)); + ctx.LoadValue(valueFrom); + if (!read) // write requires the object for StartSubItem; read doesn't + { // (if recursion-check is disabled [subtypes] then null is fine too) + if (Helpers.IsValueType(type) || !recursionCheck) { ctx.LoadNullRef(); } + else { ctx.CopyValue(); } + } + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(rwType, "StartSubItem", + read ? new Type[] { rwType } : new Type[] { ctx.MapType(typeof(object)), rwType })); + ctx.StoreValue(token); + + // note: value already on the stack + ctx.LoadReaderWriter(); + ctx.EmitCall(method); + // handle inheritance (we will be calling the *base* version of things, + // but we expect Read to return the "type" type) + if (read && type != method.ReturnType) ctx.Cast(this.type); + ctx.LoadValue(token); + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(rwType, "EndSubItem", new Type[] { ctx.MapType(typeof(SubItemToken)), rwType })); + } + return true; + } + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (!EmitDedicatedMethod(ctx, valueFrom, false)) + { + ctx.LoadValue(valueFrom); + if (Helpers.IsValueType(type)) ctx.CastToObject(type); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoWriter)), recursionCheck ? "WriteObject" : "WriteRecursionSafeObject", new Type[] { ctx.MapType(typeof(object)), ctx.MapType(typeof(int)), ctx.MapType(typeof(ProtoWriter)) })); + } + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (!EmitDedicatedMethod(ctx, valueFrom, true)) + { + ctx.LoadValue(valueFrom); + if (Helpers.IsValueType(type)) ctx.CastToObject(type); + ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method + ctx.LoadReaderWriter(); + ctx.EmitCall(Helpers.GetStaticMethod(ctx.MapType(typeof(ProtoReader)), "ReadObject")); + ctx.CastFromObject(type); + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta new file mode 100644 index 00000000..aaeac6f7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SubItemSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d29a14abe6c62349930c948a6d438c4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs new file mode 100644 index 00000000..86275eb8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs @@ -0,0 +1,157 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class SurrogateSerializer : IProtoTypeSerializer + { + bool IProtoTypeSerializer.HasCallbacks(ProtoBuf.Meta.TypeModel.CallbackType callbackType) { return false; } +#if FEAT_COMPILER + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, ProtoBuf.Meta.TypeModel.CallbackType callbackType) { } + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); } +#endif + bool IProtoTypeSerializer.CanCreateInstance() => false; + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) => throw new NotSupportedException(); + + void IProtoTypeSerializer.Callback(object value, ProtoBuf.Meta.TypeModel.CallbackType callbackType, SerializationContext context) { } + + public bool ReturnsValue => false; + + public bool RequiresOldValue => true; + + public Type ExpectedType => forType; + + private readonly Type forType, declaredType; + private readonly MethodInfo toTail, fromTail; + IProtoTypeSerializer rootTail; + + public SurrogateSerializer(TypeModel model, Type forType, Type declaredType, IProtoTypeSerializer rootTail) + { + Helpers.DebugAssert(forType != null, "forType"); + Helpers.DebugAssert(declaredType != null, "declaredType"); + Helpers.DebugAssert(rootTail != null, "rootTail"); + Helpers.DebugAssert(rootTail.RequiresOldValue, "RequiresOldValue"); + Helpers.DebugAssert(!rootTail.ReturnsValue, "ReturnsValue"); + Helpers.DebugAssert(declaredType == rootTail.ExpectedType || Helpers.IsSubclassOf(declaredType, rootTail.ExpectedType)); + this.forType = forType; + this.declaredType = declaredType; + this.rootTail = rootTail; + toTail = GetConversion(model, true); + fromTail = GetConversion(model, false); + } + private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op) + { +#if PROFILE259 + System.Collections.Generic.List list = new System.Collections.Generic.List(); + foreach (var item in type.GetRuntimeMethods()) + { + if (item.IsStatic) list.Add(item); + } + MethodInfo[] found = list.ToArray(); +#else + const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + MethodInfo[] found = type.GetMethods(flags); +#endif + ParameterInfo[] paramTypes; + Type convertAttributeType = null; + for (int i = 0; i < found.Length; i++) + { + MethodInfo m = found[i]; + if (m.ReturnType != to) continue; + paramTypes = m.GetParameters(); + if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from) + { + if (convertAttributeType == null) + { + convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false); + if (convertAttributeType == null) + { // attribute isn't defined in the source assembly: stop looking + break; + } + } + if (m.IsDefined(convertAttributeType, true)) + { + op = m; + return true; + } + } + } + + for (int i = 0; i < found.Length; i++) + { + MethodInfo m = found[i]; + if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to) + { + continue; + } + paramTypes = m.GetParameters(); + if (paramTypes.Length == 1 && paramTypes[0].ParameterType == from) + { + op = m; + return true; + } + } + op = null; + return false; + } + + public MethodInfo GetConversion(TypeModel model, bool toTail) + { + Type to = toTail ? declaredType : forType; + Type from = toTail ? forType : declaredType; + MethodInfo op; + if (HasCast(model, declaredType, from, to, out op) || HasCast(model, forType, from, to, out op)) + { + return op; + } + throw new InvalidOperationException("No suitable conversion operator found for surrogate: " + + forType.FullName + " / " + declaredType.FullName); + } + + public void Write(object value, ProtoWriter writer) + { + rootTail.Write(toTail.Invoke(null, new object[] { value }), writer); + } + + public object Read(object value, ProtoReader source) + { + // convert the incoming value + object[] args = { value }; + value = toTail.Invoke(null, args); + + // invoke the tail and convert the outgoing value + args[0] = rootTail.Read(value, source); + return fromTail.Invoke(null, args); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Helpers.DebugAssert(valueFrom != null); // don't support stack-head for this + using (Compiler.Local converted = new Compiler.Local(ctx, declaredType)) // declare/re-use local + { + ctx.LoadValue(valueFrom); // load primary onto stack + ctx.EmitCall(toTail); // static convert op, primary-to-surrogate + ctx.StoreValue(converted); // store into surrogate local + + rootTail.EmitRead(ctx, converted); // downstream processing against surrogate local + + ctx.LoadValue(converted); // load from surrogate local + ctx.EmitCall(fromTail); // static convert op, surrogate-to-primary + ctx.StoreValue(valueFrom); // store back into primary + } + } + + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.EmitCall(toTail); + rootTail.EmitWrite(ctx, null); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta new file mode 100644 index 00000000..39cf4192 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SurrogateSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 517911a690de2bd4c97e81f35104a81a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs new file mode 100644 index 00000000..4b1656da --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs @@ -0,0 +1,46 @@ +using System; + +#if !NO_RUNTIME + +namespace ProtoBuf.Serializers +{ + sealed class SystemTypeSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(Type); + + public SystemTypeSerializer(ProtoBuf.Meta.TypeModel model) + { + + } + + public Type ExpectedType => expectedType; + + void IProtoSerializer.Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteType((Type)value, dest); + } + + object IProtoSerializer.Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadType(); + } + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteType", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadType", ExpectedType); + } +#endif + } +} + +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta new file mode 100644 index 00000000..4f43a1fe --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/SystemTypeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f3b3869287521554a816dba994928f83 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TagDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TagDecorator.cs new file mode 100644 index 00000000..509b8a0f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TagDecorator.cs @@ -0,0 +1,108 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class TagDecorator : ProtoDecoratorBase, IProtoTypeSerializer + { + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; + return pts != null && pts.HasCallbacks(callbackType); + } + + public bool CanCreateInstance() + { + IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; + return pts != null && pts.CanCreateInstance(); + } + + public object CreateInstance(ProtoReader source) + { + return ((IProtoTypeSerializer)Tail).CreateInstance(source); + } + + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + if (Tail is IProtoTypeSerializer pts) + { + pts.Callback(value, callbackType, context); + } + } + +#if FEAT_COMPILER + public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + // we only expect this to be invoked if HasCallbacks returned true, so implicitly Tail + // **must** be of the correct type + ((IProtoTypeSerializer)Tail).EmitCallback(ctx, valueFrom, callbackType); + } + + public void EmitCreateInstance(Compiler.CompilerContext ctx) + { + ((IProtoTypeSerializer)Tail).EmitCreateInstance(ctx); + } +#endif + public override Type ExpectedType => Tail.ExpectedType; + + public TagDecorator(int fieldNumber, WireType wireType, bool strict, IProtoSerializer tail) + : base(tail) + { + this.fieldNumber = fieldNumber; + this.wireType = wireType; + this.strict = strict; + } + + public override bool RequiresOldValue => Tail.RequiresOldValue; + + public override bool ReturnsValue => Tail.ReturnsValue; + + private readonly bool strict; + private readonly int fieldNumber; + private readonly WireType wireType; + + private bool NeedsHint => ((int)wireType & ~7) != 0; + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(fieldNumber == source.FieldNumber); + if (strict) { source.Assert(wireType); } + else if (NeedsHint) { source.Hint(wireType); } + return Tail.Read(value, source); + } + + public override void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); + Tail.Write(value, dest); + } + + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue((int)fieldNumber); + ctx.LoadValue((int)wireType); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); + Tail.EmitWrite(ctx, valueFrom); + } + + protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) + { + if (strict || NeedsHint) + { + ctx.LoadReaderWriter(); + ctx.LoadValue((int)wireType); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod(strict ? "Assert" : "Hint")); + } + Tail.EmitRead(ctx, valueFrom); + } +#endif + } + +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta new file mode 100644 index 00000000..e522eda7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TagDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f807f0cbd3358f6479b78ab47c89ad48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs new file mode 100644 index 00000000..4c8b828e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs @@ -0,0 +1,63 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class TimeSpanSerializer : IProtoSerializer + { + static readonly Type expectedType = typeof(TimeSpan); + private readonly bool wellKnown; + public TimeSpanSerializer(DataFormat dataFormat, ProtoBuf.Meta.TypeModel model) + { + + wellKnown = dataFormat == DataFormat.WellKnown; + } + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + if (wellKnown) + { + return BclHelpers.ReadDuration(source); + } + else + { + Helpers.DebugAssert(value == null); // since replaces + return BclHelpers.ReadTimeSpan(source); + } + } + + public void Write(object value, ProtoWriter dest) + { + if (wellKnown) + { + BclHelpers.WriteDuration((TimeSpan)value, dest); + } + else + { + BclHelpers.WriteTimeSpan((TimeSpan)value, dest); + } + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.WriteDuration) : nameof(BclHelpers.WriteTimeSpan), valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + if (wellKnown) ctx.LoadValue(valueFrom); + ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), + wellKnown ? nameof(BclHelpers.ReadDuration) : nameof(BclHelpers.ReadTimeSpan), + ExpectedType); + } +#endif + + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta new file mode 100644 index 00000000..013bd6ef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TimeSpanSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 88ce40638421a9d4abd295d84d1991e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs new file mode 100644 index 00000000..b6f9c696 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs @@ -0,0 +1,339 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; +using ProtoBuf.Meta; + +namespace ProtoBuf.Serializers +{ + sealed class TupleSerializer : IProtoTypeSerializer + { + private readonly MemberInfo[] members; + private readonly ConstructorInfo ctor; + private IProtoSerializer[] tails; + public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members) + { + this.ctor = ctor ?? throw new ArgumentNullException(nameof(ctor)); + this.members = members ?? throw new ArgumentNullException(nameof(members)); + this.tails = new IProtoSerializer[members.Length]; + + ParameterInfo[] parameters = ctor.GetParameters(); + for (int i = 0; i < members.Length; i++) + { + WireType wireType; + Type finalType = parameters[i].ParameterType; + + Type itemType = null, defaultType = null; + + MetaType.ResolveListTypes(model, finalType, ref itemType, ref defaultType); + Type tmp = itemType == null ? finalType : itemType; + + bool asReference = false; + int typeIndex = model.FindOrAddAuto(tmp, false, true, false); + if (typeIndex >= 0) + { + asReference = model[tmp].AsReferenceDefault; + } + IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, false, false, true), serializer; + if (tail == null) + { + throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName); + } + + tail = new TagDecorator(i + 1, wireType, false, tail); + if (itemType == null) + { + serializer = tail; + } + else + { + if (finalType.IsArray) + { + serializer = new ArrayDecorator(model, tail, i + 1, false, wireType, finalType, false, false); + } + else + { + serializer = ListDecorator.Create(model, finalType, defaultType, tail, i + 1, false, wireType, true, false, false); + } + } + tails[i] = serializer; + } + } + public bool HasCallbacks(Meta.TypeModel.CallbackType callbackType) + { + return false; + } + +#if FEAT_COMPILER + public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, Meta.TypeModel.CallbackType callbackType) { } +#endif + public Type ExpectedType => ctor.DeclaringType; + + void IProtoTypeSerializer.Callback(object value, Meta.TypeModel.CallbackType callbackType, SerializationContext context) { } + object IProtoTypeSerializer.CreateInstance(ProtoReader source) { throw new NotSupportedException(); } + private object GetValue(object obj, int index) + { + PropertyInfo prop; + FieldInfo field; + + if ((prop = members[index] as PropertyInfo) != null) + { + if (obj == null) + return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null; + return prop.GetValue(obj, null); + } + else if ((field = members[index] as FieldInfo) != null) + { + if (obj == null) + return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null; + return field.GetValue(obj); + } + else + { + throw new InvalidOperationException(); + } + } + + public object Read(object value, ProtoReader source) + { + object[] values = new object[members.Length]; + bool invokeCtor = false; + if (value == null) + { + invokeCtor = true; + } + for (int i = 0; i < values.Length; i++) + values[i] = GetValue(value, i); + int field; + while ((field = source.ReadFieldHeader()) > 0) + { + invokeCtor = true; + if (field <= tails.Length) + { + IProtoSerializer tail = tails[field - 1]; + values[field - 1] = tails[field - 1].Read(tail.RequiresOldValue ? values[field - 1] : null, source); + } + else + { + source.SkipField(); + } + } + return invokeCtor ? ctor.Invoke(values) : value; + } + + public void Write(object value, ProtoWriter dest) + { + for (int i = 0; i < tails.Length; i++) + { + object val = GetValue(value, i); + if (val != null) tails[i].Write(val, dest); + } + } + + public bool RequiresOldValue => true; + + public bool ReturnsValue => false; + + Type GetMemberType(int index) + { + Type result = Helpers.GetMemberType(members[index]); + if (result == null) throw new InvalidOperationException(); + return result; + } + + bool IProtoTypeSerializer.CanCreateInstance() { return false; } + +#if FEAT_COMPILER + public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + using (Compiler.Local loc = ctx.GetLocalWithValue(ctor.DeclaringType, valueFrom)) + { + for (int i = 0; i < tails.Length; i++) + { + Type type = GetMemberType(i); + ctx.LoadAddress(loc, ExpectedType); + if (members[i] is FieldInfo) + { + ctx.LoadValue((FieldInfo)members[i]); + } + else if (members[i] is PropertyInfo) + { + ctx.LoadValue((PropertyInfo)members[i]); + } + ctx.WriteNullCheckedTail(type, tails[i], null); + } + } + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); } + + public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local incoming) + { + using (Compiler.Local objValue = ctx.GetLocalWithValue(ExpectedType, incoming)) + { + Compiler.Local[] locals = new Compiler.Local[members.Length]; + try + { + for (int i = 0; i < locals.Length; i++) + { + Type type = GetMemberType(i); + bool store = true; + locals[i] = new Compiler.Local(ctx, type); + if (!Helpers.IsValueType(ExpectedType)) + { + // value-types always read the old value + if (Helpers.IsValueType(type)) + { + switch (Helpers.GetTypeCode(type)) + { + case ProtoTypeCode.Boolean: + case ProtoTypeCode.Byte: + case ProtoTypeCode.Int16: + case ProtoTypeCode.Int32: + case ProtoTypeCode.SByte: + case ProtoTypeCode.UInt16: + case ProtoTypeCode.UInt32: + ctx.LoadValue(0); + break; + case ProtoTypeCode.Int64: + case ProtoTypeCode.UInt64: + ctx.LoadValue(0L); + break; + case ProtoTypeCode.Single: + ctx.LoadValue(0.0F); + break; + case ProtoTypeCode.Double: + ctx.LoadValue(0.0D); + break; + case ProtoTypeCode.Decimal: + ctx.LoadValue(0M); + break; + case ProtoTypeCode.Guid: + ctx.LoadValue(Guid.Empty); + break; + default: + ctx.LoadAddress(locals[i], type); + ctx.EmitCtor(type); + store = false; + break; + } + } + else + { + ctx.LoadNullRef(); + } + if (store) + { + ctx.StoreValue(locals[i]); + } + } + } + + Compiler.CodeLabel skipOld = Helpers.IsValueType(ExpectedType) + ? new Compiler.CodeLabel() + : ctx.DefineLabel(); + if (!Helpers.IsValueType(ExpectedType)) + { + ctx.LoadAddress(objValue, ExpectedType); + ctx.BranchIfFalse(skipOld, false); + } + for (int i = 0; i < members.Length; i++) + { + ctx.LoadAddress(objValue, ExpectedType); + if (members[i] is FieldInfo) + { + ctx.LoadValue((FieldInfo)members[i]); + } + else if (members[i] is PropertyInfo) + { + ctx.LoadValue((PropertyInfo)members[i]); + } + ctx.StoreValue(locals[i]); + } + + if (!Helpers.IsValueType(ExpectedType)) ctx.MarkLabel(skipOld); + + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + Compiler.CodeLabel @continue = ctx.DefineLabel(), + processField = ctx.DefineLabel(), + notRecognised = ctx.DefineLabel(); + ctx.Branch(@continue, false); + + Compiler.CodeLabel[] handlers = new Compiler.CodeLabel[members.Length]; + for (int i = 0; i < members.Length; i++) + { + handlers[i] = ctx.DefineLabel(); + } + + ctx.MarkLabel(processField); + + ctx.LoadValue(fieldNumber); + ctx.LoadValue(1); + ctx.Subtract(); // jump-table is zero-based + ctx.Switch(handlers); + + // and the default: + ctx.Branch(notRecognised, false); + for (int i = 0; i < handlers.Length; i++) + { + ctx.MarkLabel(handlers[i]); + IProtoSerializer tail = tails[i]; + Compiler.Local oldValIfNeeded = tail.RequiresOldValue ? locals[i] : null; + ctx.ReadNullCheckedTail(locals[i].Type, tail, oldValIfNeeded); + if (tail.ReturnsValue) + { + if (Helpers.IsValueType(locals[i].Type)) + { + ctx.StoreValue(locals[i]); + } + else + { + Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel(); + + ctx.CopyValue(); + ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign" + ctx.DiscardValue(); + ctx.Branch(allDone, true); + ctx.MarkLabel(hasValue); + ctx.StoreValue(locals[i]); + ctx.MarkLabel(allDone); + } + } + ctx.Branch(@continue, false); + } + + ctx.MarkLabel(notRecognised); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + + ctx.MarkLabel(@continue); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(fieldNumber); + ctx.LoadValue(0); + ctx.BranchIfGreater(processField, false); + } + for (int i = 0; i < locals.Length; i++) + { + ctx.LoadValue(locals[i]); + } + + ctx.EmitCtor(ctor); + ctx.StoreValue(objValue); + } + finally + { + for (int i = 0; i < locals.Length; i++) + { + if (locals[i] != null) + locals[i].Dispose(); // release for re-use + } + } + } + + } +#endif + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta new file mode 100644 index 00000000..df99bbe6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TupleSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e57d0cd813299f40a1a32236d9931a9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs new file mode 100644 index 00000000..d851b47f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs @@ -0,0 +1,798 @@ +#if !NO_RUNTIME +using System; +using ProtoBuf.Meta; +#if FEAT_COMPILER + +#endif + +using System.Reflection; + +namespace ProtoBuf.Serializers +{ + sealed class TypeSerializer : IProtoTypeSerializer + { + public bool HasCallbacks(TypeModel.CallbackType callbackType) + { + if (callbacks != null && callbacks[callbackType] != null) return true; + for (int i = 0; i < serializers.Length; i++) + { + if (serializers[i].ExpectedType != forType && ((IProtoTypeSerializer)serializers[i]).HasCallbacks(callbackType)) return true; + } + return false; + } + private readonly Type forType, constructType; +#if COREFX || PROFILE259 + private readonly TypeInfo typeInfo; +#endif + public Type ExpectedType { get { return forType; } } + private readonly IProtoSerializer[] serializers; + private readonly int[] fieldNumbers; + private readonly bool isRootType, useConstructor, isExtensible, hasConstructor; + private readonly CallbackSet callbacks; + private readonly MethodInfo[] baseCtorCallbacks; + private readonly MethodInfo factory; + public TypeSerializer(TypeModel model, Type forType, int[] fieldNumbers, IProtoSerializer[] serializers, MethodInfo[] baseCtorCallbacks, bool isRootType, bool useConstructor, CallbackSet callbacks, Type constructType, MethodInfo factory) + { + Helpers.DebugAssert(forType != null); + Helpers.DebugAssert(fieldNumbers != null); + Helpers.DebugAssert(serializers != null); + Helpers.DebugAssert(fieldNumbers.Length == serializers.Length); + + Helpers.Sort(fieldNumbers, serializers); + bool hasSubTypes = false; + for (int i = 0; i < fieldNumbers.Length; i++) + { + if (i != 0 && fieldNumbers[i] == fieldNumbers[i - 1]) throw new InvalidOperationException("Duplicate field-number detected; " + + fieldNumbers[i].ToString() + " on: " + forType.FullName); + if (!hasSubTypes && serializers[i].ExpectedType != forType) + { + hasSubTypes = true; + } + } + this.forType = forType; + this.factory = factory; +#if COREFX || PROFILE259 + this.typeInfo = forType.GetTypeInfo(); +#endif + if (constructType == null) + { + constructType = forType; + } + else + { +#if COREFX || PROFILE259 + if (!typeInfo.IsAssignableFrom(constructType.GetTypeInfo())) +#else + if (!forType.IsAssignableFrom(constructType)) +#endif + { + throw new InvalidOperationException(forType.FullName + " cannot be assigned from " + constructType.FullName); + } + } + this.constructType = constructType; + this.serializers = serializers; + this.fieldNumbers = fieldNumbers; + this.callbacks = callbacks; + this.isRootType = isRootType; + this.useConstructor = useConstructor; + + if (baseCtorCallbacks != null && baseCtorCallbacks.Length == 0) baseCtorCallbacks = null; + this.baseCtorCallbacks = baseCtorCallbacks; + + if (Helpers.GetUnderlyingType(forType) != null) + { + throw new ArgumentException("Cannot create a TypeSerializer for nullable types", "forType"); + } + +#if COREFX || PROFILE259 + if (iextensible.IsAssignableFrom(typeInfo)) + { + if (typeInfo.IsValueType || !isRootType || hasSubTypes) +#else + if (model.MapType(iextensible).IsAssignableFrom(forType)) + { + if (forType.IsValueType || !isRootType || hasSubTypes) +#endif + { + throw new NotSupportedException("IExtensible is not supported in structs or classes with inheritance"); + } + isExtensible = true; + } +#if COREFX || PROFILE259 + TypeInfo constructTypeInfo = constructType.GetTypeInfo(); + hasConstructor = !constructTypeInfo.IsAbstract && Helpers.GetConstructor(constructTypeInfo, Helpers.EmptyTypes, true) != null; +#else + hasConstructor = !constructType.IsAbstract && Helpers.GetConstructor(constructType, Helpers.EmptyTypes, true) != null; +#endif + if (constructType != forType && useConstructor && !hasConstructor) + { + throw new ArgumentException("The supplied default implementation cannot be created: " + constructType.FullName, "constructType"); + } + } +#if COREFX || PROFILE259 + private static readonly TypeInfo iextensible = typeof(IExtensible).GetTypeInfo(); +#else + private static readonly System.Type iextensible = typeof(IExtensible); +#endif + + private bool CanHaveInheritance + { + get + { +#if COREFX || PROFILE259 + return (typeInfo.IsClass || typeInfo.IsInterface) && !typeInfo.IsSealed; +#else + return (forType.IsClass || forType.IsInterface) && !forType.IsSealed; +#endif + } + } + + bool IProtoTypeSerializer.CanCreateInstance() { return true; } + + object IProtoTypeSerializer.CreateInstance(ProtoReader source) + { + return CreateInstance(source, false); + } + public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) + { + if (callbacks != null) InvokeCallback(callbacks[callbackType], value, context); + IProtoTypeSerializer ser = (IProtoTypeSerializer)GetMoreSpecificSerializer(value); + if (ser != null) ser.Callback(value, callbackType, context); + } + private IProtoSerializer GetMoreSpecificSerializer(object value) + { + if (!CanHaveInheritance) return null; + Type actualType = value.GetType(); + if (actualType == forType) return null; + + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType != forType && Helpers.IsAssignableFrom(ser.ExpectedType, actualType)) + { + return ser; + } + } + if (actualType == constructType) return null; // needs to be last in case the default concrete type is also a known sub-type + TypeModel.ThrowUnexpectedSubtype(forType, actualType); // might throw (if not a proxy) + return null; + } + + public void Write(object value, ProtoWriter dest) + { + if (isRootType) Callback(value, TypeModel.CallbackType.BeforeSerialize, dest.Context); + // write inheritance first + IProtoSerializer next = GetMoreSpecificSerializer(value); + if (next != null) next.Write(value, dest); + + // write all actual fields + //Helpers.DebugWriteLine(">> Writing fields for " + forType.FullName); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType == forType) + { + //Helpers.DebugWriteLine(": " + ser.ToString()); + ser.Write(value, dest); + } + } + //Helpers.DebugWriteLine("<< Writing fields for " + forType.FullName); + if (isExtensible) ProtoWriter.AppendExtensionData((IExtensible)value, dest); + if (isRootType) Callback(value, TypeModel.CallbackType.AfterSerialize, dest.Context); + } + + public object Read(object value, ProtoReader source) + { + if (isRootType && value != null) { Callback(value, TypeModel.CallbackType.BeforeDeserialize, source.Context); } + int fieldNumber, lastFieldNumber = 0, lastFieldIndex = 0; + bool fieldHandled; + + //Helpers.DebugWriteLine(">> Reading fields for " + forType.FullName); + while ((fieldNumber = source.ReadFieldHeader()) > 0) + { + fieldHandled = false; + if (fieldNumber < lastFieldNumber) + { + lastFieldNumber = lastFieldIndex = 0; + } + for (int i = lastFieldIndex; i < fieldNumbers.Length; i++) + { + if (fieldNumbers[i] == fieldNumber) + { + IProtoSerializer ser = serializers[i]; + //Helpers.DebugWriteLine(": " + ser.ToString()); + Type serType = ser.ExpectedType; + if (value == null) + { + if (serType == forType) value = CreateInstance(source, true); + } + else + { + if (serType != forType && ((IProtoTypeSerializer)ser).CanCreateInstance() + && serType +#if COREFX || PROFILE259 + .GetTypeInfo() +#endif + .IsSubclassOf(value.GetType())) + { + value = ProtoReader.Merge(source, value, ((IProtoTypeSerializer)ser).CreateInstance(source)); + } + } + + if (ser.ReturnsValue) + { + value = ser.Read(value, source); + } + else + { // pop + ser.Read(value, source); + } + + lastFieldIndex = i; + lastFieldNumber = fieldNumber; + fieldHandled = true; + break; + } + } + if (!fieldHandled) + { + //Helpers.DebugWriteLine(": [" + fieldNumber + "] (unknown)"); + if (value == null) value = CreateInstance(source, true); + if (isExtensible) + { + source.AppendExtensionData((IExtensible)value); + } + else + { + source.SkipField(); + } + } + } + //Helpers.DebugWriteLine("<< Reading fields for " + forType.FullName); + if (value == null) value = CreateInstance(source, true); + if (isRootType) { Callback(value, TypeModel.CallbackType.AfterDeserialize, source.Context); } + return value; + } + + private object InvokeCallback(MethodInfo method, object obj, SerializationContext context) + { + object result = null; + object[] args; + if (method != null) + { // pass in a streaming context if one is needed, else null + bool handled; + ParameterInfo[] parameters = method.GetParameters(); + switch (parameters.Length) + { + case 0: + args = null; + handled = true; + break; + default: + args = new object[parameters.Length]; + handled = true; + for (int i = 0; i < args.Length; i++) + { + object val; + Type paramType = parameters[i].ParameterType; + if (paramType == typeof(SerializationContext)) val = context; + else if (paramType == typeof(System.Type)) val = constructType; +#if PLAT_BINARYFORMATTER + else if (paramType == typeof(System.Runtime.Serialization.StreamingContext)) val = (System.Runtime.Serialization.StreamingContext)context; +#endif + else + { + val = null; + handled = false; + } + args[i] = val; + } + break; + } + if (handled) + { + result = method.Invoke(obj, args); + } + else + { + throw Meta.CallbackSet.CreateInvalidCallbackSignature(method); + } + + } + return result; + } + object CreateInstance(ProtoReader source, bool includeLocalCallback) + { + //Helpers.DebugWriteLine("* creating : " + forType.FullName); + object obj; + if (factory != null) + { + obj = InvokeCallback(factory, null, source.Context); + } + else if (useConstructor) + { + if (!hasConstructor) TypeModel.ThrowCannotCreateInstance(constructType); +#if PROFILE259 + ConstructorInfo constructorInfo = System.Linq.Enumerable.First( + constructType.GetTypeInfo().DeclaredConstructors, c => c.GetParameters().Length == 0); + obj = constructorInfo.Invoke(new object[] {}); + +#else + obj = Activator.CreateInstance(constructType +#if !(CF || PORTABLE || NETSTANDARD1_3 || NETSTANDARD1_4 || UAP) + , nonPublic: true +#endif + ); +#endif + } + else + { + obj = BclHelpers.GetUninitializedObject(constructType); + } + ProtoReader.NoteObject(obj, source); + if (baseCtorCallbacks != null) + { + for (int i = 0; i < baseCtorCallbacks.Length; i++) + { + InvokeCallback(baseCtorCallbacks[i], obj, source.Context); + } + } + if (includeLocalCallback && callbacks != null) InvokeCallback(callbacks.BeforeDeserialize, obj, source.Context); + return obj; + } + + bool IProtoSerializer.RequiresOldValue { get { return true; } } + bool IProtoSerializer.ReturnsValue { get { return false; } } // updates field directly +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Type expected = ExpectedType; + using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom)) + { + // pre-callbacks + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeSerialize); + + Compiler.CodeLabel startFields = ctx.DefineLabel(); + // inheritance + if (CanHaveInheritance) + { + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + Type serType = ser.ExpectedType; + if (serType != forType) + { + Compiler.CodeLabel ifMatch = ctx.DefineLabel(), nextTest = ctx.DefineLabel(); + ctx.LoadValue(loc); + ctx.TryCast(serType); + ctx.CopyValue(); + ctx.BranchIfTrue(ifMatch, true); + ctx.DiscardValue(); + ctx.Branch(nextTest, true); + ctx.MarkLabel(ifMatch); + if (Helpers.IsValueType(serType)) + { + ctx.DiscardValue(); + ctx.LoadValue(loc); + ctx.CastFromObject(serType); + } + ser.EmitWrite(ctx, null); + ctx.Branch(startFields, false); + ctx.MarkLabel(nextTest); + } + } + + + if (constructType != null && constructType != forType) + { + using (Compiler.Local actualType = new Compiler.Local(ctx, ctx.MapType(typeof(System.Type)))) + { + // would have jumped to "fields" if an expected sub-type, so two options: + // a: *exactly* that type, b: an *unexpected* type + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.CopyValue(); + ctx.StoreValue(actualType); + ctx.LoadValue(forType); + ctx.BranchIfEqual(startFields, true); + + ctx.LoadValue(actualType); + ctx.LoadValue(constructType); + ctx.BranchIfEqual(startFields, true); + } + } + else + { + // would have jumped to "fields" if an expected sub-type, so two options: + // a: *exactly* that type, b: an *unexpected* type + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.LoadValue(forType); + ctx.BranchIfEqual(startFields, true); + } + // unexpected, then... note that this *might* be a proxy, which + // is handled by ThrowUnexpectedSubtype + ctx.LoadValue(forType); + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType")); + ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowUnexpectedSubtype", + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)); + + } + // fields + + ctx.MarkLabel(startFields); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType == forType) ser.EmitWrite(ctx, loc); + } + + // extension data + if (isExtensible) + { + ctx.LoadValue(loc); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("AppendExtensionData")); + } + // post-callbacks + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterSerialize); + } + } + static void EmitInvokeCallback(Compiler.CompilerContext ctx, MethodInfo method, bool copyValue, Type constructType, Type type) + { + if (method != null) + { + if (copyValue) ctx.CopyValue(); // assumes the target is on the stack, and that we want to *retain* it on the stack + ParameterInfo[] parameters = method.GetParameters(); + bool handled = true; + + for (int i = 0; i < parameters.Length; i++) + { + Type parameterType = parameters[i].ParameterType; + if (parameterType == ctx.MapType(typeof(SerializationContext))) + { + ctx.LoadSerializationContext(); + } + else if (parameterType == ctx.MapType(typeof(System.Type))) + { + Type tmp = constructType; + if (tmp == null) tmp = type; // no ?? in some C# profiles + ctx.LoadValue(tmp); + } +#if PLAT_BINARYFORMATTER + else if (parameterType == ctx.MapType(typeof(System.Runtime.Serialization.StreamingContext))) + { + ctx.LoadSerializationContext(); + MethodInfo op = ctx.MapType(typeof(SerializationContext)).GetMethod("op_Implicit", new Type[] { ctx.MapType(typeof(SerializationContext)) }); + if (op != null) + { // it isn't always! (framework versions, etc) + ctx.EmitCall(op); + handled = true; + } + } +#endif + else + { + handled = false; + } + } + if (handled) + { + ctx.EmitCall(method); + if (constructType != null) + { + if (method.ReturnType == ctx.MapType(typeof(object))) + { + ctx.CastFromObject(type); + } + } + } + else + { + throw Meta.CallbackSet.CreateInvalidCallbackSignature(method); + } + } + } + + private void EmitCallbackIfNeeded(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + Helpers.DebugAssert(valueFrom != null); + if (isRootType && ((IProtoTypeSerializer)this).HasCallbacks(callbackType)) + { + ((IProtoTypeSerializer)this).EmitCallback(ctx, valueFrom, callbackType); + } + } + + void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) + { + bool actuallyHasInheritance = false; + if (CanHaveInheritance) + { + + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + if (ser.ExpectedType != forType && ((IProtoTypeSerializer)ser).HasCallbacks(callbackType)) + { + actuallyHasInheritance = true; + } + } + } + + Helpers.DebugAssert(((IProtoTypeSerializer)this).HasCallbacks(callbackType), "Shouldn't be calling this if there is nothing to do"); + MethodInfo method = callbacks?[callbackType]; + if (method == null && !actuallyHasInheritance) + { + return; + } + ctx.LoadAddress(valueFrom, ExpectedType); + EmitInvokeCallback(ctx, method, actuallyHasInheritance, null, forType); + + if (actuallyHasInheritance) + { + Compiler.CodeLabel @break = ctx.DefineLabel(); + for (int i = 0; i < serializers.Length; i++) + { + IProtoSerializer ser = serializers[i]; + IProtoTypeSerializer typeser; + Type serType = ser.ExpectedType; + if (serType != forType && + (typeser = (IProtoTypeSerializer)ser).HasCallbacks(callbackType)) + { + Compiler.CodeLabel ifMatch = ctx.DefineLabel(), nextTest = ctx.DefineLabel(); + ctx.CopyValue(); + ctx.TryCast(serType); + ctx.CopyValue(); + ctx.BranchIfTrue(ifMatch, true); + ctx.DiscardValue(); + ctx.Branch(nextTest, false); + ctx.MarkLabel(ifMatch); + typeser.EmitCallback(ctx, null, callbackType); + ctx.Branch(@break, false); + ctx.MarkLabel(nextTest); + } + } + ctx.MarkLabel(@break); + ctx.DiscardValue(); + } + } + + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Type expected = ExpectedType; + Helpers.DebugAssert(valueFrom != null); + + using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom)) + using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) + { + // pre-callbacks + if (HasCallbacks(TypeModel.CallbackType.BeforeDeserialize)) + { + if (Helpers.IsValueType(ExpectedType)) + { + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize); + } + else + { // could be null + Compiler.CodeLabel callbacksDone = ctx.DefineLabel(); + ctx.LoadValue(loc); + ctx.BranchIfFalse(callbacksDone, false); + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize); + ctx.MarkLabel(callbacksDone); + } + } + + Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel(); + ctx.Branch(@continue, false); + + ctx.MarkLabel(processField); + foreach (BasicList.Group group in BasicList.GetContiguousGroups(fieldNumbers, serializers)) + { + Compiler.CodeLabel tryNextField = ctx.DefineLabel(); + int groupItemCount = group.Items.Count; + if (groupItemCount == 1) + { + // discreet group; use an equality test + ctx.LoadValue(fieldNumber); + ctx.LoadValue(group.First); + Compiler.CodeLabel processThisField = ctx.DefineLabel(); + ctx.BranchIfEqual(processThisField, true); + ctx.Branch(tryNextField, false); + WriteFieldHandler(ctx, expected, loc, processThisField, @continue, (IProtoSerializer)group.Items[0]); + } + else + { // implement as a jump-table-based switch + ctx.LoadValue(fieldNumber); + ctx.LoadValue(group.First); + ctx.Subtract(); // jump-tables are zero-based + Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount]; + for (int i = 0; i < groupItemCount; i++) + { + jmp[i] = ctx.DefineLabel(); + } + ctx.Switch(jmp); + // write the default... + ctx.Branch(tryNextField, false); + for (int i = 0; i < groupItemCount; i++) + { + WriteFieldHandler(ctx, expected, loc, jmp[i], @continue, (IProtoSerializer)group.Items[i]); + } + } + ctx.MarkLabel(tryNextField); + } + + EmitCreateIfNull(ctx, loc); + ctx.LoadReaderWriter(); + if (isExtensible) + { + ctx.LoadValue(loc); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendExtensionData")); + } + else + { + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); + } + + ctx.MarkLabel(@continue); + ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); + ctx.CopyValue(); + ctx.StoreValue(fieldNumber); + ctx.LoadValue(0); + ctx.BranchIfGreater(processField, false); + + EmitCreateIfNull(ctx, loc); + // post-callbacks + EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterDeserialize); + + if (valueFrom != null && !loc.IsSame(valueFrom)) + { + ctx.LoadValue(loc); + ctx.Cast(valueFrom.Type); + ctx.StoreValue(valueFrom); + } + } + } + + private void WriteFieldHandler( + Compiler.CompilerContext ctx, Type expected, Compiler.Local loc, + Compiler.CodeLabel handler, Compiler.CodeLabel @continue, IProtoSerializer serializer) + { + ctx.MarkLabel(handler); + Type serType = serializer.ExpectedType; + if (serType == forType) + { + EmitCreateIfNull(ctx, loc); + serializer.EmitRead(ctx, loc); + } + else + { + //RuntimeTypeModel rtm = (RuntimeTypeModel)ctx.Model; + if (((IProtoTypeSerializer)serializer).CanCreateInstance()) + { + Compiler.CodeLabel allDone = ctx.DefineLabel(); + + ctx.LoadValue(loc); + ctx.BranchIfFalse(allDone, false); // null is always ok + + ctx.LoadValue(loc); + ctx.TryCast(serType); + ctx.BranchIfTrue(allDone, false); // not null, but of the correct type + + // otherwise, need to convert it + ctx.LoadReaderWriter(); + ctx.LoadValue(loc); + ((IProtoTypeSerializer)serializer).EmitCreateInstance(ctx); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("Merge")); + ctx.Cast(expected); + ctx.StoreValue(loc); // Merge always returns a value + + // nothing needs doing + ctx.MarkLabel(allDone); + } + + if (Helpers.IsValueType(serType)) + { + Compiler.CodeLabel initValue = ctx.DefineLabel(); + Compiler.CodeLabel hasValue = ctx.DefineLabel(); + using (Compiler.Local emptyValue = new Compiler.Local(ctx, serType)) + { + ctx.LoadValue(loc); + ctx.BranchIfFalse(initValue, false); + + ctx.LoadValue(loc); + ctx.CastFromObject(serType); + ctx.Branch(hasValue, false); + + ctx.MarkLabel(initValue); + ctx.InitLocal(serType, emptyValue); + ctx.LoadValue(emptyValue); + + ctx.MarkLabel(hasValue); + } + } + else + { + ctx.LoadValue(loc); + ctx.Cast(serType); + } + + serializer.EmitRead(ctx, null); + + } + + if (serializer.ReturnsValue) + { // update the variable + if (Helpers.IsValueType(serType)) + { + // but box it first in case of value type + ctx.CastToObject(serType); + } + ctx.StoreValue(loc); + } + ctx.Branch(@continue, false); // "continue" + } + + void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) + { + // different ways of creating a new instance + bool callNoteObject = true; + if (factory != null) + { + EmitInvokeCallback(ctx, factory, false, constructType, forType); + } + else if (!useConstructor) + { // DataContractSerializer style + ctx.LoadValue(constructType); + ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("GetUninitializedObject")); + ctx.Cast(forType); + } + else if (Helpers.IsClass(constructType) && hasConstructor) + { // XmlSerializer style + ctx.EmitCtor(constructType); + } + else + { + ctx.LoadValue(ExpectedType); + ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowCannotCreateInstance", + BindingFlags.Static | BindingFlags.Public)); + ctx.LoadNullRef(); + callNoteObject = false; + } + if (callNoteObject) + { + // track root object creation + ctx.CopyValue(); + ctx.LoadReaderWriter(); + ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("NoteObject", + BindingFlags.Static | BindingFlags.Public)); + } + if (baseCtorCallbacks != null) + { + for (int i = 0; i < baseCtorCallbacks.Length; i++) + { + EmitInvokeCallback(ctx, baseCtorCallbacks[i], true, null, forType); + } + } + } + private void EmitCreateIfNull(Compiler.CompilerContext ctx, Compiler.Local storage) + { + Helpers.DebugAssert(storage != null); + if (!Helpers.IsValueType(ExpectedType)) + { + Compiler.CodeLabel afterNullCheck = ctx.DefineLabel(); + ctx.LoadValue(storage); + ctx.BranchIfTrue(afterNullCheck, false); + + ((IProtoTypeSerializer)this).EmitCreateInstance(ctx); + + if (callbacks != null) EmitInvokeCallback(ctx, callbacks.BeforeDeserialize, true, null, forType); + ctx.StoreValue(storage); + ctx.MarkLabel(afterNullCheck); + } + } +#endif + } + +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta new file mode 100644 index 00000000..0b9bc498 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/TypeSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b3f577c98285d56469b3eb1c9190e174 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs new file mode 100644 index 00000000..ff9f89b7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + class UInt16Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(ushort); + + public UInt16Serializer(ProtoBuf.Meta.TypeModel model) + { + } + + public virtual Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public virtual object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadUInt16(); + } + + public virtual void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt16((ushort)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt16", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt16", ctx.MapType(typeof(ushort))); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta new file mode 100644 index 00000000..3e94120a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt16Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 95fff5b2239c48c4cbb32346fee1be94 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs new file mode 100644 index 00000000..08b4f4bb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class UInt32Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(uint); + + public UInt32Serializer(ProtoBuf.Meta.TypeModel model) + { + + } + + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadUInt32(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt32((uint)value, dest); + } +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt32", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt32", ctx.MapType(typeof(uint))); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta new file mode 100644 index 00000000..342cdec7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt32Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79149f5f69e868c45a17d389322e4bb7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs new file mode 100644 index 00000000..8577eddc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs @@ -0,0 +1,43 @@ +#if !NO_RUNTIME +using System; + +namespace ProtoBuf.Serializers +{ + sealed class UInt64Serializer : IProtoSerializer + { + static readonly Type expectedType = typeof(ulong); + + public UInt64Serializer(ProtoBuf.Meta.TypeModel model) + { + + } + public Type ExpectedType => expectedType; + + bool IProtoSerializer.RequiresOldValue => false; + + bool IProtoSerializer.ReturnsValue => true; + + public object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // since replaces + return source.ReadUInt64(); + } + + public void Write(object value, ProtoWriter dest) + { + ProtoWriter.WriteUInt64((ulong)value, dest); + } + +#if FEAT_COMPILER + void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicWrite("WriteUInt64", valueFrom); + } + void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.EmitBasicRead("ReadUInt64", ExpectedType); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta new file mode 100644 index 00000000..72452d9c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UInt64Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e549c20b3409c4a4dbf0e7fc25062c71 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UriDecorator.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UriDecorator.cs new file mode 100644 index 00000000..d34ac2df --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UriDecorator.cs @@ -0,0 +1,62 @@ +#if !NO_RUNTIME +using System; +using System.Reflection; + +#if FEAT_COMPILER +using ProtoBuf.Compiler; +#endif + +namespace ProtoBuf.Serializers +{ + sealed class UriDecorator : ProtoDecoratorBase + { + static readonly Type expectedType = typeof(Uri); + public UriDecorator(ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail) + { + + } + + public override Type ExpectedType => expectedType; + + public override bool RequiresOldValue => false; + + public override bool ReturnsValue => true; + + public override void Write(object value, ProtoWriter dest) + { + Tail.Write(((Uri)value).OriginalString, dest); + } + + public override object Read(object value, ProtoReader source) + { + Helpers.DebugAssert(value == null); // not expecting incoming + string s = (string)Tail.Read(null, source); + return s.Length == 0 ? null : new Uri(s, UriKind.RelativeOrAbsolute); + } + +#if FEAT_COMPILER + protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + ctx.LoadValue(valueFrom); + ctx.LoadValue(typeof(Uri).GetProperty("OriginalString")); + Tail.EmitWrite(ctx, null); + } + protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) + { + Tail.EmitRead(ctx, valueFrom); + ctx.CopyValue(); + Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel(); + ctx.LoadValue(typeof(string).GetProperty("Length")); + ctx.BranchIfTrue(@nonEmpty, true); + ctx.DiscardValue(); + ctx.LoadNullRef(); + ctx.Branch(@end, true); + ctx.MarkLabel(@nonEmpty); + ctx.LoadValue((int)UriKind.RelativeOrAbsolute); + ctx.EmitCtor(ctx.MapType(typeof(Uri)), ctx.MapType(typeof(string)), ctx.MapType(typeof(UriKind))); + ctx.MarkLabel(@end); + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta new file mode 100644 index 00000000..0095ee9f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/Serializers/UriDecorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b784c432eb5cbf742b3d96161e7c8d73 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel.meta new file mode 100644 index 00000000..36e1d951 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: af34a7ba57dbd6340b8d3fa0bfdbd0a1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs new file mode 100644 index 00000000..928207e7 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs @@ -0,0 +1,35 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System; +using System.ServiceModel.Channels; +using System.ServiceModel.Description; +using System.ServiceModel.Dispatcher; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Uses protocol buffer serialization on the specified operation; note that this + /// must be enabled on both the client and server. + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public sealed class ProtoBehaviorAttribute : Attribute, IOperationBehavior + { + void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) + { } + + void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) + { + IOperationBehavior innerBehavior = new ProtoOperationBehavior(operationDescription); + innerBehavior.ApplyClientBehavior(operationDescription, clientOperation); + } + + void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) + { + IOperationBehavior innerBehavior = new ProtoOperationBehavior(operationDescription); + innerBehavior.ApplyDispatchBehavior(operationDescription, dispatchOperation); + } + + void IOperationBehavior.Validate(OperationDescription operationDescription) + { } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta new file mode 100644 index 00000000..1facc701 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: feda16667cbcb8248951368dfbfef6b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs new file mode 100644 index 00000000..56edb792 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs @@ -0,0 +1,29 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER && FEAT_SERVICECONFIGMODEL +using System; +using System.ServiceModel.Configuration; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Configuration element to swap out DatatContractSerilaizer with the XmlProtoSerializer for a given endpoint. + /// + /// + public class ProtoBehaviorExtension : BehaviorExtensionElement + { + /// + /// Creates a new ProtoBehaviorExtension instance. + /// + public ProtoBehaviorExtension() { } + /// + /// Gets the type of behavior. + /// + public override Type BehaviorType => typeof(ProtoEndpointBehavior); + + /// + /// Creates a behavior extension based on the current configuration settings. + /// + /// The behavior extension. + protected override object CreateBehavior() => new ProtoEndpointBehavior(); + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta new file mode 100644 index 00000000..7850781f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c70aaa3829dd1fa45b0530efc37727f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs new file mode 100644 index 00000000..9bcfb995 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs @@ -0,0 +1,82 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System.ServiceModel.Description; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Behavior to swap out DatatContractSerilaizer with the XmlProtoSerializer for a given endpoint. + /// + /// Add the following to the server and client app.config in the system.serviceModel section: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Configure your endpoints to have a behaviorConfiguration as follows: + /// + /// + /// + /// + /// + /// + /// + /// + /// + public class ProtoEndpointBehavior : IEndpointBehavior + { + #region IEndpointBehavior Members + + void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) + { + } + + void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) + { + ReplaceDataContractSerializerOperationBehavior(endpoint); + } + + void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) + { + ReplaceDataContractSerializerOperationBehavior(endpoint); + } + + void IEndpointBehavior.Validate(ServiceEndpoint endpoint) + { + } + + private static void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint serviceEndpoint) + { + foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations) + { + ReplaceDataContractSerializerOperationBehavior(operationDescription); + } + } + + private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description) + { + DataContractSerializerOperationBehavior dcsOperationBehavior = description.Behaviors.Find(); + if (dcsOperationBehavior != null) + { + description.Behaviors.Remove(dcsOperationBehavior); + + ProtoOperationBehavior newBehavior = new ProtoOperationBehavior(description); + newBehavior.MaxItemsInObjectGraph = dcsOperationBehavior.MaxItemsInObjectGraph; + description.Behaviors.Add(newBehavior); + } + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta new file mode 100644 index 00000000..23ab7835 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoEndpointBehavior.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6776c4cee4f69a94e9507afa458fdb50 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs new file mode 100644 index 00000000..9d5f02c6 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs @@ -0,0 +1,52 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.ServiceModel.Description; +using System.Xml; +using ProtoBuf.Meta; + +namespace ProtoBuf.ServiceModel +{ + /// + /// Describes a WCF operation behaviour that can perform protobuf serialization + /// + public sealed class ProtoOperationBehavior : DataContractSerializerOperationBehavior + { + private TypeModel model; + + /// + /// Create a new ProtoOperationBehavior instance + /// + public ProtoOperationBehavior(OperationDescription operation) : base(operation) + { +#if !NO_RUNTIME + model = RuntimeTypeModel.Default; +#endif + } + + /// + /// The type-model that should be used with this behaviour + /// + public TypeModel Model + { + get { return model; } + set + { + model = value ?? throw new ArgumentNullException(nameof(value)); + } + } + + //public ProtoOperationBehavior(OperationDescription operation, DataContractFormatAttribute dataContractFormat) : base(operation, dataContractFormat) { } + + /// + /// Creates a protobuf serializer if possible (falling back to the default WCF serializer) + /// + public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList knownTypes) + { + if (model == null) throw new InvalidOperationException("No Model instance has been assigned to the ProtoOperationBehavior"); + return XmlProtoSerializer.TryCreate(model, type) ?? base.CreateSerializer(type, name, ns, knownTypes); + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta new file mode 100644 index 00000000..3bd6fe4e --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/ProtoOperationBehavior.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc6637ab509d5ba41b14e428ed365764 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs new file mode 100644 index 00000000..23959eaf --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs @@ -0,0 +1,208 @@ +#if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER +using System; +using System.IO; +using System.Runtime.Serialization; +using System.Xml; +using ProtoBuf.Meta; + +namespace ProtoBuf.ServiceModel +{ + /// + /// An xml object serializer that can embed protobuf data in a base-64 hunk (looking like a byte[]) + /// + public sealed class XmlProtoSerializer : XmlObjectSerializer + { + private readonly TypeModel model; + private readonly int key; + private readonly bool isList, isEnum; + private readonly Type type; + internal XmlProtoSerializer(TypeModel model, int key, Type type, bool isList) + { + if (key < 0) throw new ArgumentOutOfRangeException(nameof(key)); + this.model = model ?? throw new ArgumentNullException(nameof(model)); + this.key = key; + this.isList = isList; + this.type = type ?? throw new ArgumentOutOfRangeException(nameof(type)); + this.isEnum = Helpers.IsEnum(type); + } + /// + /// Attempt to create a new serializer for the given model and type + /// + /// A new serializer instance if the type is recognised by the model; null otherwise + public static XmlProtoSerializer TryCreate(TypeModel model, Type type) + { + if (model == null) throw new ArgumentNullException(nameof(model)); + if (type == null) throw new ArgumentNullException(nameof(type)); + + int key = GetKey(model, ref type, out bool isList); + if (key >= 0) + { + return new XmlProtoSerializer(model, key, type, isList); + } + return null; + } + + /// + /// Creates a new serializer for the given model and type + /// + public XmlProtoSerializer(TypeModel model, Type type) + { + if (model == null) throw new ArgumentNullException(nameof(model)); + if (type == null) throw new ArgumentNullException(nameof(type)); + + key = GetKey(model, ref type, out isList); + this.model = model; + this.type = type; + this.isEnum = Helpers.IsEnum(type); + if (key < 0) throw new ArgumentOutOfRangeException(nameof(type), "Type not recognised by the model: " + type.FullName); + } + + static int GetKey(TypeModel model, ref Type type, out bool isList) + { + if (model != null && type != null) + { + int key = model.GetKey(ref type); + if (key >= 0) + { + isList = false; + return key; + } + Type itemType = TypeModel.GetListItemType(model, type); + if (itemType != null) + { + key = model.GetKey(ref itemType); + if (key >= 0) + { + isList = true; + return key; + } + } + } + + isList = false; + return -1; + } + + /// + /// Ends an object in the output + /// + public override void WriteEndObject(XmlDictionaryWriter writer) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + writer.WriteEndElement(); + } + + /// + /// Begins an object in the output + /// + public override void WriteStartObject(XmlDictionaryWriter writer, object graph) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + writer.WriteStartElement(PROTO_ELEMENT); + } + + private const string PROTO_ELEMENT = "proto"; + + /// + /// Writes the body of an object in the output + /// + public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) + { + if (writer == null) throw new ArgumentNullException(nameof(writer)); + if (graph == null) + { + writer.WriteAttributeString("nil", "true"); + } + else + { + using (MemoryStream ms = new MemoryStream()) + { + if (isList) + { + model.Serialize(ms, graph, null); + } + else + { + using (ProtoWriter protoWriter = ProtoWriter.Create(ms, model, null)) + { + model.Serialize(key, graph, protoWriter); + } + } + byte[] buffer = ms.GetBuffer(); + writer.WriteBase64(buffer, 0, (int)ms.Length); + } + } + } + + /// + /// Indicates whether this is the start of an object we are prepared to handle + /// + public override bool IsStartObject(XmlDictionaryReader reader) + { + if (reader == null) throw new ArgumentNullException(nameof(reader)); + reader.MoveToContent(); + return reader.NodeType == XmlNodeType.Element && reader.Name == PROTO_ELEMENT; + } + + /// + /// Reads the body of an object + /// + public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) + { + if (reader == null) throw new ArgumentNullException(nameof(reader)); + reader.MoveToContent(); + bool isSelfClosed = reader.IsEmptyElement, isNil = reader.GetAttribute("nil") == "true"; + reader.ReadStartElement(PROTO_ELEMENT); + + // explicitly null + if (isNil) + { + if (!isSelfClosed) reader.ReadEndElement(); + return null; + } + if (isSelfClosed) // no real content + { + if (isList || isEnum) + { + return model.Deserialize(Stream.Null, null, type, null); + } + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(Stream.Null, model, null, ProtoReader.TO_EOF); + return model.Deserialize(key, null, protoReader); + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + + object result; + Helpers.DebugAssert(reader.CanReadBinaryContent, "CanReadBinaryContent"); + using (MemoryStream ms = new MemoryStream(reader.ReadContentAsBase64())) + { + if (isList || isEnum) + { + result = model.Deserialize(ms, null, type, null); + } + else + { + ProtoReader protoReader = null; + try + { + protoReader = ProtoReader.Create(ms, model, null, ProtoReader.TO_EOF); + result = model.Deserialize(key, null, protoReader); + } + finally + { + ProtoReader.Recycle(protoReader); + } + } + } + reader.ReadEndElement(); + return result; + } + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta new file mode 100644 index 00000000..d564f13b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/ServiceModel/XmlProtoSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bca9bc75e9bb7c841b04b85204a0c9f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SubItemToken.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SubItemToken.cs new file mode 100644 index 00000000..51f4a24a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SubItemToken.cs @@ -0,0 +1,16 @@ + +using System; + +namespace ProtoBuf +{ + /// + /// Used to hold particulars relating to nested objects. This is opaque to the caller - simply + /// give back the token you are given at the end of an object. + /// + public readonly struct SubItemToken + { + internal readonly long value64; + internal SubItemToken(int value) => value64 = value; + internal SubItemToken(long value) => value64 = value; + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SubItemToken.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SubItemToken.cs.meta new file mode 100644 index 00000000..75435a12 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/SubItemToken.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bbb510795b4f3fa46aeecbd4521adfc0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/WireType.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/WireType.cs new file mode 100644 index 00000000..ab4fa205 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/WireType.cs @@ -0,0 +1,50 @@ +namespace ProtoBuf +{ + /// + /// Indicates the encoding used to represent an individual value in a protobuf stream + /// + public enum WireType + { + /// + /// Represents an error condition + /// + None = -1, + + /// + /// Base-128 variant-length encoding + /// + Variant = 0, + + /// + /// Fixed-length 8-byte encoding + /// + Fixed64 = 1, + + /// + /// Length-variant-prefixed encoding + /// + String = 2, + + /// + /// Indicates the start of a group + /// + StartGroup = 3, + + /// + /// Indicates the end of a group + /// + EndGroup = 4, + + /// + /// Fixed-length 4-byte encoding + /// 10 + Fixed32 = 5, + + /// + /// This is not a formal wire-type in the "protocol buffers" spec, but + /// denotes a variant integer that should be interpreted using + /// zig-zag semantics (so -ve numbers aren't a significant overhead) + /// + SignedVariant = WireType.Variant | (1 << 3), + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/WireType.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/WireType.cs.meta new file mode 100644 index 00000000..25660263 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/WireType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a8403cbfeff31942997d1726a909e89 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/protobuf-net.csproj b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/protobuf-net.csproj new file mode 100644 index 00000000..e72f4abb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/protobuf-net.csproj @@ -0,0 +1,86 @@ + + + protobuf-net + protobuf-net + Provides simple access to fast and efficient "Protocol Buffers" serialization from .NET applications + net20;net35;net452;netstandard2.0;netcoreapp3.1 + true + EMIT_ASSEMBLY_INFO + + True + + + net + true + true + true + true + true + Debug;Release;VS + + + + false + + + false + false + false + false + $(DefineConstants);COREFX;UAP + + + $(DefineConstants);COREFX + standard + true + false + + + $(DefineConstants);COREFX + none + true + false + + + + $(DefineConstants);FEAT_COMPILER + + + $(DefineConstants);FEAT_SERVICEMODEL + + + $(DefineConstants);FEAT_SERVICECONFIGMODEL + + + $(DefineConstants);PLAT_XMLSERIALIZER + + + $(DefineConstants);PLAT_BINARYFORMATTER + + + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/protobuf-net.csproj.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/protobuf-net.csproj.meta new file mode 100644 index 00000000..0950983a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/Protobuf-net/protobuf-net.csproj.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3b9128b665b538746a11489aee369030 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket.meta new file mode 100644 index 00000000..d5dbe805 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fa968f65de2ed4f10a755c0646cde595 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core.meta new file mode 100644 index 00000000..75a53494 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8b3a2a8f55d4a47f599b1fa3ed612389 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseEventArgs.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseEventArgs.cs new file mode 100644 index 00000000..d0d5831a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseEventArgs.cs @@ -0,0 +1,89 @@ +using System; + +namespace UnityWebSocket +{ + /// + /// Represents the event data for the event. + /// + /// + /// + /// That event occurs when the WebSocket connection has been closed. + /// + /// + /// If you would like to get the reason for the close, you should access + /// the or property. + /// + /// + public class CloseEventArgs : EventArgs + { + #region Internal Constructors + + internal CloseEventArgs() + { + } + + internal CloseEventArgs(ushort code) + : this(code, null) + { + } + + internal CloseEventArgs(CloseStatusCode code) + : this((ushort)code, null) + { + } + + internal CloseEventArgs(CloseStatusCode code, string reason) + : this((ushort)code, reason) + { + } + + internal CloseEventArgs(ushort code, string reason) + { + Code = code; + Reason = reason; + } + + #endregion + + #region Public Properties + + /// + /// Gets the status code for the close. + /// + /// + /// A that represents the status code for the close if any. + /// + public ushort Code { get; private set; } + + /// + /// Gets the reason for the close. + /// + /// + /// A that represents the reason for the close if any. + /// + public string Reason { get; private set; } + + /// + /// Gets a value indicating whether the connection has been closed cleanly. + /// + /// + /// true if the connection has been closed cleanly; otherwise, false. + /// + public bool WasClean { get; internal set; } + + /// + /// Enum value same as Code + /// + public CloseStatusCode StatusCode + { + get + { + if (Enum.IsDefined(typeof(CloseStatusCode), Code)) + return (CloseStatusCode)Code; + return CloseStatusCode.Unknown; + } + } + + #endregion + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseEventArgs.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseEventArgs.cs.meta new file mode 100644 index 00000000..6e2a928a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29b987d07ba15434cb1744135a7a5416 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseStatusCode.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseStatusCode.cs new file mode 100644 index 00000000..0da2ddbd --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseStatusCode.cs @@ -0,0 +1,91 @@ +namespace UnityWebSocket +{ + /// + /// Indicates the status code for the WebSocket connection close. + /// + /// + /// + /// The values of this enumeration are defined in + /// + /// Section 7.4 of RFC 6455. + /// + /// + /// "Reserved value" cannot be sent as a status code in + /// closing handshake by an endpoint. + /// + /// + public enum CloseStatusCode : ushort + { + Unknown = 65534, + /// + /// Equivalent to close status 1000. Indicates normal close. + /// + Normal = 1000, + /// + /// Equivalent to close status 1001. Indicates that an endpoint is + /// going away. + /// + Away = 1001, + /// + /// Equivalent to close status 1002. Indicates that an endpoint is + /// terminating the connection due to a protocol error. + /// + ProtocolError = 1002, + /// + /// Equivalent to close status 1003. Indicates that an endpoint is + /// terminating the connection because it has received a type of + /// data that it cannot accept. + /// + UnsupportedData = 1003, + /// + /// Equivalent to close status 1004. Still undefined. A Reserved value. + /// + Undefined = 1004, + /// + /// Equivalent to close status 1005. Indicates that no status code was + /// actually present. A Reserved value. + /// + NoStatus = 1005, + /// + /// Equivalent to close status 1006. Indicates that the connection was + /// closed abnormally. A Reserved value. + /// + Abnormal = 1006, + /// + /// Equivalent to close status 1007. Indicates that an endpoint is + /// terminating the connection because it has received a message that + /// contains data that is not consistent with the type of the message. + /// + InvalidData = 1007, + /// + /// Equivalent to close status 1008. Indicates that an endpoint is + /// terminating the connection because it has received a message that + /// violates its policy. + /// + PolicyViolation = 1008, + /// + /// Equivalent to close status 1009. Indicates that an endpoint is + /// terminating the connection because it has received a message that + /// is too big to process. + /// + TooBig = 1009, + /// + /// Equivalent to close status 1010. Indicates that a client is + /// terminating the connection because it has expected the server to + /// negotiate one or more extension, but the server did not return + /// them in the handshake response. + /// + MandatoryExtension = 1010, + /// + /// Equivalent to close status 1011. Indicates that a server is + /// terminating the connection because it has encountered an unexpected + /// condition that prevented it from fulfilling the request. + /// + ServerError = 1011, + /// + /// Equivalent to close status 1015. Indicates that the connection was + /// closed due to a failure to perform a TLS handshake. A Reserved value. + /// + TlsHandshakeFailure = 1015, + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseStatusCode.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseStatusCode.cs.meta new file mode 100644 index 00000000..48e96605 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/CloseStatusCode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e34ee317292e4225a10427cc35f85ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/ErrorEventArgs.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/ErrorEventArgs.cs new file mode 100644 index 00000000..cfb91b87 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/ErrorEventArgs.cs @@ -0,0 +1,59 @@ +using System; + +namespace UnityWebSocket +{ + /// + /// Represents the event data for the event. + /// + /// + /// + /// That event occurs when the gets an error. + /// + /// + /// If you would like to get the error message, you should access + /// the property. + /// + /// + /// And if the error is due to an exception, you can get it by accessing + /// the property. + /// + /// + public class ErrorEventArgs : EventArgs + { + #region Internal Constructors + + internal ErrorEventArgs(string message) + : this(message, null) + { + } + + internal ErrorEventArgs(string message, Exception exception) + { + this.Message = message; + this.Exception = exception; + } + + #endregion + + #region Public Properties + + /// + /// Gets the exception that caused the error. + /// + /// + /// An instance that represents the cause of + /// the error if it is due to an exception; otherwise, . + /// + public Exception Exception { get; private set; } + + /// + /// Gets the error message. + /// + /// + /// A that represents the error message. + /// + public string Message { get; private set; } + + #endregion + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta new file mode 100644 index 00000000..47a5055b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/ErrorEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 884e7db60b6444154b7200e0e436f2de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/IWebSocket.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/IWebSocket.cs new file mode 100644 index 00000000..3e08d4b5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/IWebSocket.cs @@ -0,0 +1,143 @@ +using System; + +namespace UnityWebSocket +{ + /// + /// IWebSocket indicate a network connection. + /// It can be connecting, connected, closing or closed state. + /// You can send and receive messages by using it. + /// Register callbacks for handling messages. + /// ----------------------------------------------------------- + /// IWebSocket 表示一个网络连接, + /// 它可以是 connecting connected closing closed 状态, + /// 可以发送和接收消息, + /// 通过注册消息回调,来处理接收到的消息。 + /// + public interface IWebSocket + { + /// + /// Establishes a connection asynchronously. + /// + /// + /// + /// This method does not wait for the connect process to be complete. + /// + /// + /// This method does nothing if the connection has already been + /// established. + /// + /// + /// + /// + /// This instance is not a client. + /// + /// + /// -or- + /// + /// + /// The close process is in progress. + /// + /// + /// -or- + /// + /// + /// A series of reconnecting has failed. + /// + /// + void ConnectAsync(); + + /// + /// Closes the connection asynchronously. + /// + /// + /// + /// This method does not wait for the close to be complete. + /// + /// + /// This method does nothing if the current state of the connection is + /// Closing or Closed. + /// + /// + void CloseAsync(); + + /// + /// Sends the specified data asynchronously using the WebSocket connection. + /// + /// + /// This method does not wait for the send to be complete. + /// + /// + /// An array of that represents the binary data to send. + /// + /// + /// The current state of the connection is not Open. + /// + /// + /// is . + /// + void SendAsync(byte[] data); + + /// + /// Sends the specified data using the WebSocket connection. + /// + /// + /// A that represents the text data to send. + /// + /// + /// The current state of the connection is not Open. + /// + /// + /// is . + /// + /// + /// could not be UTF-8 encoded. + /// + void SendAsync(string text); + + /// + /// get the address which to connect. + /// + string Address { get; } + + /// + /// get sub protocols . + /// + string[] SubProtocols { get; } + + /// + /// Gets the current state of the connection. + /// + /// + /// + /// One of the enum values. + /// + /// + /// It indicates the current state of the connection. + /// + /// + /// The default value is . + /// + /// + WebSocketState ReadyState { get; } + + /// + /// Occurs when the WebSocket connection has been established. + /// + event EventHandler OnOpen; + + /// + /// Occurs when the WebSocket connection has been closed. + /// + event EventHandler OnClose; + + /// + /// Occurs when the gets an error. + /// + event EventHandler OnError; + + /// + /// Occurs when the receives a message. + /// + event EventHandler OnMessage; + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/IWebSocket.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/IWebSocket.cs.meta new file mode 100644 index 00000000..ae658256 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/IWebSocket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 37ee2146eb8c34ffab8b081a632b05cf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/MessageEventArgs.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/MessageEventArgs.cs new file mode 100644 index 00000000..a80fbae8 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/MessageEventArgs.cs @@ -0,0 +1,115 @@ +using System; +using System.Text; + +namespace UnityWebSocket +{ + public class MessageEventArgs : EventArgs + { + private byte[] _rawData; + private string _data; + + internal MessageEventArgs(Opcode opcode, byte[] rawData) + { + Opcode = opcode; + _rawData = rawData; + } + + internal MessageEventArgs(Opcode opcode, string data) + { + Opcode = opcode; + _data = data; + } + + /// + /// Gets the opcode for the message. + /// + /// + /// , . + /// + internal Opcode Opcode { get; private set; } + + /// + /// Gets the message data as a . + /// + /// + /// A that represents the message data if its type is + /// text and if decoding it to a string has successfully done; + /// otherwise, . + /// + public string Data + { + get + { + SetData(); + return _data; + } + } + + /// + /// Gets the message data as an array of . + /// + /// + /// An array of that represents the message data. + /// + public byte[] RawData + { + get + { + SetRawData(); + return _rawData; + } + } + + /// + /// Gets a value indicating whether the message type is binary. + /// + /// + /// true if the message type is binary; otherwise, false. + /// + public bool IsBinary + { + get + { + return Opcode == Opcode.Binary; + } + } + + /// + /// Gets a value indicating whether the message type is text. + /// + /// + /// true if the message type is text; otherwise, false. + /// + public bool IsText + { + get + { + return Opcode == Opcode.Text; + } + } + + private void SetData() + { + if (_data != null) return; + + if (RawData == null) + { + return; + } + + _data = Encoding.UTF8.GetString(RawData); + } + + private void SetRawData() + { + if (_rawData != null) return; + + if (_data == null) + { + return; + } + + _rawData = Encoding.UTF8.GetBytes(_data); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/MessageEventArgs.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/MessageEventArgs.cs.meta new file mode 100644 index 00000000..1c3a7d13 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/MessageEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b44eda173b4924081bab76ae9d1b0a9c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Opcode.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Opcode.cs new file mode 100644 index 00000000..3e758e23 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Opcode.cs @@ -0,0 +1,26 @@ +namespace UnityWebSocket +{ + /// + /// Indicates the WebSocket frame type. + /// + /// + /// The values of this enumeration are defined in + /// + /// Section 5.2 of RFC 6455. + /// + public enum Opcode : byte + { + /// + /// Equivalent to numeric value 1. Indicates text frame. + /// + Text = 0x1, + /// + /// Equivalent to numeric value 2. Indicates binary frame. + /// + Binary = 0x2, + /// + /// Equivalent to numeric value 8. Indicates connection close frame. + /// + Close = 0x8, + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Opcode.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Opcode.cs.meta new file mode 100644 index 00000000..a7ed802f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Opcode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eeac0ef90273544ebbae046672caf362 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/OpenEventArgs.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/OpenEventArgs.cs new file mode 100644 index 00000000..fa84a33d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/OpenEventArgs.cs @@ -0,0 +1,11 @@ +using System; + +namespace UnityWebSocket +{ + public class OpenEventArgs : EventArgs + { + internal OpenEventArgs() + { + } + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/OpenEventArgs.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/OpenEventArgs.cs.meta new file mode 100644 index 00000000..0cfe2c2d --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/OpenEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5fb6fd704bd4e4b8ba63cd0b28712955 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Settings.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Settings.cs new file mode 100644 index 00000000..95fdd230 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Settings.cs @@ -0,0 +1,12 @@ +namespace UnityWebSocket +{ + public static class Settings + { + public const string GITHUB = "https://github.com/psygames/UnityWebSocket"; + public const string QQ_GROUP = "1126457634"; + public const string QQ_GROUP_LINK = "https://qm.qq.com/cgi-bin/qm/qr?k=KcexYJ9aYwogFXbj2aN0XHH5b2G7ICmd"; + public const string EMAIL = "799329256@qq.com"; + public const string AUHTOR = "psygames"; + public const string VERSION = "2.8.5"; + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Settings.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Settings.cs.meta new file mode 100644 index 00000000..e8e36229 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/Settings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e268303c7a605e343b1b132e5559f01f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/WebSocketState.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/WebSocketState.cs new file mode 100644 index 00000000..796ab15f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/WebSocketState.cs @@ -0,0 +1,36 @@ +namespace UnityWebSocket +{ + /// + /// Reference html5 WebSocket ReadyState Properties + /// Indicates the state of a WebSocket connection. + /// + /// + /// The values of this enumeration are defined in + /// + /// The WebSocket API. + /// + public enum WebSocketState : ushort + { + /// + /// Equivalent to numeric value 0. Indicates that the connection has not + /// yet been established. + /// + Connecting = 0, + /// + /// Equivalent to numeric value 1. Indicates that the connection has + /// been established, and the communication is possible. + /// + Open = 1, + /// + /// Equivalent to numeric value 2. Indicates that the connection is + /// going through the closing handshake, or the close method has + /// been invoked. + /// + Closing = 2, + /// + /// Equivalent to numeric value 3. Indicates that the connection has + /// been closed or could not be established. + /// + Closed = 3 + } +} diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/WebSocketState.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/WebSocketState.cs.meta new file mode 100644 index 00000000..94877ec5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Core/WebSocketState.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f6567ad13cb147a59f8af784f1c5f60 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation.meta new file mode 100644 index 00000000..abb1981f --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 396c66b333d624d539153070900bb73b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL.meta new file mode 100644 index 00000000..dc70a45c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6c110a898ae8b0b41bcf4da49c2b0425 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs new file mode 100644 index 00000000..8c8256fc --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs @@ -0,0 +1,341 @@ +#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL) +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Net.WebSockets; +using System.IO; +using System.Collections.Concurrent; + +namespace UnityWebSocket +{ + public class WebSocket : IWebSocket + { + public string Address { get; private set; } + public string[] SubProtocols { get; private set; } + + public WebSocketState ReadyState + { + get + { + if (socket == null) + return WebSocketState.Closed; + switch (socket.State) + { + case System.Net.WebSockets.WebSocketState.Closed: + case System.Net.WebSockets.WebSocketState.None: + return WebSocketState.Closed; + case System.Net.WebSockets.WebSocketState.CloseReceived: + case System.Net.WebSockets.WebSocketState.CloseSent: + return WebSocketState.Closing; + case System.Net.WebSockets.WebSocketState.Connecting: + return WebSocketState.Connecting; + case System.Net.WebSockets.WebSocketState.Open: + return WebSocketState.Open; + } + return WebSocketState.Closed; + } + } + + public event EventHandler OnOpen; + public event EventHandler OnClose; + public event EventHandler OnError; + public event EventHandler OnMessage; + + private ClientWebSocket socket; + private bool isOpening => socket != null && socket.State == System.Net.WebSockets.WebSocketState.Open; + private ConcurrentQueue sendQueue = new ConcurrentQueue(); + private ConcurrentQueue eventQueue = new ConcurrentQueue(); + private bool closeProcessing; + private CancellationTokenSource cts = null; + + #region APIs + public WebSocket(string address) + { + this.Address = address; + } + + public WebSocket(string address, string subProtocol) + { + this.Address = address; + this.SubProtocols = new string[] { subProtocol }; + } + + public WebSocket(string address, string[] subProtocols) + { + this.Address = address; + this.SubProtocols = subProtocols; + } + + public void ConnectAsync() + { + if (socket != null) + { + HandleError(new Exception("Socket is busy.")); + return; + } + + WebSocketManager.Instance.Add(this); + + socket = new ClientWebSocket(); + cts = new CancellationTokenSource(); + + // support sub protocols + if (this.SubProtocols != null) + { + foreach (var protocol in this.SubProtocols) + { + if (string.IsNullOrEmpty(protocol)) continue; + Log($"Add Sub Protocol {protocol}"); + socket.Options.AddSubProtocol(protocol); + } + } + + Task.Run(ConnectTask); + } + + public void CloseAsync() + { + if (!isOpening) return; + closeProcessing = true; + } + + public void SendAsync(byte[] data, int offset, int len) + { + if (!isOpening) return; + var buffer = new SendBuffer(data, offset, len, WebSocketMessageType.Binary); + sendQueue.Enqueue(buffer); + } + + public void SendAsync(byte[] data) + { + if (!isOpening) return; + var buffer = new SendBuffer(data,0,data.Length, WebSocketMessageType.Binary); + sendQueue.Enqueue(buffer); + } + + public void SendAsync(string text) + { + if (!isOpening) return; + var data = Encoding.UTF8.GetBytes(text); + var buffer = new SendBuffer(data, 0, data.Length, WebSocketMessageType.Text); + sendQueue.Enqueue(buffer); + } + #endregion + + class SendBuffer + { + public int offset; + public int len; + public byte[] data; + public WebSocketMessageType type; + public SendBuffer(byte[] data, int offset, int len, WebSocketMessageType type) + { + this.offset = offset; + this.len = len; + this.data = data; + this.type = type; + } + } + + private void CleanSendQueue() + { + while (sendQueue.TryDequeue(out var _)) ; + } + + private void CleanEventQueue() + { + while (eventQueue.TryDequeue(out var _)) ; + } + + private async Task ConnectTask() + { + Log("Connect Task Begin ..."); + + try + { + var uri = new Uri(Address); + await socket.ConnectAsync(uri, cts.Token); + } + catch (Exception e) + { + HandleError(e); + HandleClose((ushort)CloseStatusCode.Abnormal, e.Message); + return; + } + + HandleOpen(); + + Log("Connect Task Success !"); + + StartReceiveTask(); + StartSendTask(); + } + + private async void StartSendTask() + { + Log("Send Task Begin ..."); + + try + { + while (!closeProcessing && socket != null && cts != null && !cts.IsCancellationRequested) + { + while (!closeProcessing && sendQueue.Count > 0 && sendQueue.TryDequeue(out var buffer)) + { + Log($"Send, type: {buffer.type}, size: {buffer.data.Length}, queue left: {sendQueue.Count}"); + await socket.SendAsync(new ArraySegment(buffer.data, buffer.offset, buffer.len), + buffer.type, true, cts.Token); + } + Thread.Sleep(3); + } + if (closeProcessing && socket != null && cts != null && !cts.IsCancellationRequested) + { + CleanSendQueue(); + Log($"Close Send Begin ..."); + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", cts.Token); + Log($"Close Send Success !"); + } + } + catch (Exception e) + { + HandleError(e); + } + finally + { + closeProcessing = false; + } + + Log("Send Task End !"); + } + + private async void StartReceiveTask() + { + Log("Receive Task Begin ..."); + + string closeReason = ""; + ushort closeCode = 0; + bool isClosed = false; + var segment = new ArraySegment(new byte[8192]); + var ms = new MemoryStream(); + + try + { + while (!isClosed && !cts.IsCancellationRequested) + { + var result = await socket.ReceiveAsync(segment, cts.Token); + ms.Write(segment.Array, 0, result.Count); + if (!result.EndOfMessage) continue; + var data = ms.ToArray(); + ms.SetLength(0); + switch (result.MessageType) + { + case WebSocketMessageType.Binary: + HandleMessage(Opcode.Binary, data); + break; + case WebSocketMessageType.Text: + HandleMessage(Opcode.Text, data); + break; + case WebSocketMessageType.Close: + isClosed = true; + closeCode = (ushort)result.CloseStatus; + closeReason = result.CloseStatusDescription; + break; + } + } + } + catch (Exception e) + { + HandleError(e); + closeCode = (ushort)CloseStatusCode.Abnormal; + closeReason = e.Message; + } + finally + { + ms.Close(); + } + + HandleClose(closeCode, closeReason); + + Log("Receive Task End !"); + } + + private void SocketDispose() + { + Log("Dispose"); + WebSocketManager.Instance.Remove(this); + CleanSendQueue(); + CleanEventQueue(); + socket.Dispose(); + socket = null; + cts.Dispose(); + cts = null; + } + + private void HandleOpen() + { + Log("OnOpen"); + eventQueue.Enqueue(new OpenEventArgs()); + } + + private void HandleMessage(Opcode opcode, byte[] rawData) + { + Log($"OnMessage, type: {opcode}, size: {rawData.Length}"); + eventQueue.Enqueue(new MessageEventArgs(opcode, rawData)); + } + + private void HandleClose(ushort code, string reason) + { + Log($"OnClose, code: {code}, reason: {reason}"); + eventQueue.Enqueue(new CloseEventArgs(code, reason)); + } + + private void HandleError(Exception exception) + { + Log("OnError, error: " + exception.Message); + eventQueue.Enqueue(new ErrorEventArgs(exception.Message)); + } + + internal void Update() + { + while (eventQueue.Count > 0 && eventQueue.TryDequeue(out var e)) + { + if (e is CloseEventArgs) + { + OnClose?.Invoke(this, e as CloseEventArgs); + SocketDispose(); + break; + } + else if (e is OpenEventArgs) + { + OnOpen?.Invoke(this, e as OpenEventArgs); + } + else if (e is MessageEventArgs) + { + OnMessage?.Invoke(this, e as MessageEventArgs); + } + else if (e is ErrorEventArgs) + { + OnError?.Invoke(this, e as ErrorEventArgs); + } + } + } + + internal void Abort() + { + Log("Abort"); + if (cts != null) + { + cts.Cancel(); + } + } + + [System.Diagnostics.Conditional("UNITY_WEB_SOCKET_LOG")] + static void Log(string msg) + { + var time = DateTime.Now.ToString("HH:mm:ss.fff"); + var thread = Thread.CurrentThread.ManagedThreadId; + UnityEngine.Debug.Log($"[{time}][UnityWebSocket][T-{thread:D3}] {msg}"); + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta new file mode 100644 index 00000000..cbb5e53a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d10f88a23641b4beb8df74460fb7f705 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs new file mode 100644 index 00000000..edc79d4a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs @@ -0,0 +1,74 @@ +#if !NET_LEGACY && (UNITY_EDITOR || !UNITY_WEBGL) +using System.Collections.Generic; +using UnityEngine; + +namespace UnityWebSocket +{ + [DisallowMultipleComponent] + [DefaultExecutionOrder(-10000)] + internal class WebSocketManager : MonoBehaviour + { + private const string rootName = "[UnityWebSocket]"; + private static WebSocketManager _instance; + public static WebSocketManager Instance + { + get + { + if (!_instance) CreateInstance(); + return _instance; + } + } + + private void Awake() + { + DontDestroyOnLoad(gameObject); + } + + public static void CreateInstance() + { + GameObject go = GameObject.Find("/" + rootName); + if (!go) go = new GameObject(rootName); + _instance = go.GetComponent(); + if (!_instance) _instance = go.AddComponent(); + } + + private readonly List sockets = new List(); + + public void Add(WebSocket socket) + { + if (!sockets.Contains(socket)) + sockets.Add(socket); + } + + public void Remove(WebSocket socket) + { + if (sockets.Contains(socket)) + sockets.Remove(socket); + } + + private void Update() + { + if (sockets.Count <= 0) return; + for (int i = sockets.Count - 1; i >= 0; i--) + { + sockets[i].Update(); + } + } + +#if UNITY_EDITOR + private void OnDisable() + { + SocketAbort(); + } + + private void SocketAbort() + { + for (int i = sockets.Count - 1; i >= 0; i--) + { + sockets[i].Abort(); + } + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta new file mode 100644 index 00000000..1e26dc8c --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/NoWebGL/WebSocketManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 99157fb5def394c83a9e5342036c92b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL.meta new file mode 100644 index 00000000..e9c4e7b5 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1fb37927ec1ce4def9c5e7cff883f9f5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs new file mode 100644 index 00000000..59a98b80 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs @@ -0,0 +1,154 @@ +#if !UNITY_EDITOR && UNITY_WEBGL +using System; + +namespace UnityWebSocket +{ + public class WebSocket : IWebSocket + { + public string Address { get; private set; } + public string[] SubProtocols { get; private set; } + public WebSocketState ReadyState { get { return (WebSocketState)WebSocketManager.WebSocketGetState(instanceId); } } + + public event EventHandler OnOpen; + public event EventHandler OnClose; + public event EventHandler OnError; + public event EventHandler OnMessage; + + internal int instanceId = 0; + + public WebSocket(string address) + { + this.Address = address; + AllocateInstance(); + } + + public WebSocket(string address, string subProtocol) + { + this.Address = address; + this.SubProtocols = new string[] { subProtocol }; + AllocateInstance(); + } + + public WebSocket(string address, string[] subProtocols) + { + this.Address = address; + this.SubProtocols = subProtocols; + AllocateInstance(); + } + + internal void AllocateInstance() + { + instanceId = WebSocketManager.AllocateInstance(this.Address); + Log($"Allocate socket with instanceId: {instanceId}"); + if (this.SubProtocols == null) return; + foreach (var protocol in this.SubProtocols) + { + if (string.IsNullOrEmpty(protocol)) continue; + Log($"Add Sub Protocol {protocol}, with instanceId: {instanceId}"); + int code = WebSocketManager.WebSocketAddSubProtocol(instanceId, protocol); + if (code < 0) + { + HandleOnError(GetErrorMessageFromCode(code)); + break; + } + } + } + + ~WebSocket() + { + Log($"Free socket with instanceId: {instanceId}"); + WebSocketManager.WebSocketFree(instanceId); + } + + public void ConnectAsync() + { + Log($"Connect with instanceId: {instanceId}"); + WebSocketManager.Add(this); + int code = WebSocketManager.WebSocketConnect(instanceId); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void CloseAsync() + { + Log($"Close with instanceId: {instanceId}"); + int code = WebSocketManager.WebSocketClose(instanceId, (int)CloseStatusCode.Normal, "Normal Closure"); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void SendAsync(string text) + { + Log($"Send, type: {Opcode.Text}, size: {text.Length}"); + int code = WebSocketManager.WebSocketSendStr(instanceId, text); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void SendAsync(byte[] data) + { + Log($"Send, type: {Opcode.Binary}, size: {data.Length}"); + int code = WebSocketManager.WebSocketSend(instanceId, data, 0, data.Length); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + public void SendAsync(byte[] data, int offset, int len) + { + Log($"Send, type: {Opcode.Binary}, offset: {offset}, len: {len}, size: {data.Length}"); + int code = WebSocketManager.WebSocketSend(instanceId, data, offset, len); + if (code < 0) HandleOnError(GetErrorMessageFromCode(code)); + } + + internal void HandleOnOpen() + { + Log("OnOpen"); + OnOpen?.Invoke(this, new OpenEventArgs()); + } + + internal void HandleOnMessage(byte[] rawData) + { + Log($"OnMessage, type: {Opcode.Binary}, size: {rawData.Length}"); + OnMessage?.Invoke(this, new MessageEventArgs(Opcode.Binary, rawData)); + } + + internal void HandleOnMessageStr(string data) + { + Log($"OnMessage, type: {Opcode.Text}, size: {data.Length}"); + OnMessage?.Invoke(this, new MessageEventArgs(Opcode.Text, data)); + } + + internal void HandleOnClose(ushort code, string reason) + { + Log($"OnClose, code: {code}, reason: {reason}"); + OnClose?.Invoke(this, new CloseEventArgs(code, reason)); + WebSocketManager.Remove(instanceId); + } + + internal void HandleOnError(string msg) + { + Log("OnError, error: " + msg); + OnError?.Invoke(this, new ErrorEventArgs(msg)); + } + + internal static string GetErrorMessageFromCode(int errorCode) + { + switch (errorCode) + { + case -1: return "WebSocket instance not found."; + case -2: return "WebSocket is already connected or in connecting state."; + case -3: return "WebSocket is not connected."; + case -4: return "WebSocket is already closing."; + case -5: return "WebSocket is already closed."; + case -6: return "WebSocket is not in open state."; + case -7: return "Cannot close WebSocket, An invalid code was specified or reason is too long."; + case -8: return "Not support buffer slice. "; + default: return $"Unknown error code {errorCode}."; + } + } + + [System.Diagnostics.Conditional("UNITY_WEB_SOCKET_LOG")] + static void Log(string msg) + { + var time = DateTime.Now.ToString("HH:mm:ss.fff"); + UnityEngine.Debug.Log($"[{time}][UnityWebSocket] {msg}"); + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta new file mode 100644 index 00000000..ffe47c74 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocket.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 74a5b3c22251243d2a2f33e74741559d +timeCreated: 1466578513 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs new file mode 100644 index 00000000..d2646a2a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs @@ -0,0 +1,153 @@ +#if !UNITY_EDITOR && UNITY_WEBGL +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using AOT; + +namespace UnityWebSocket +{ + /// + /// Class providing static access methods to work with JSLIB WebSocket + /// + internal static class WebSocketManager + { + /* Map of websocket instances */ + private static Dictionary sockets = new Dictionary(); + + /* Delegates */ + public delegate void OnOpenCallback(int instanceId); + public delegate void OnMessageCallback(int instanceId, IntPtr msgPtr, int msgSize); + public delegate void OnMessageStrCallback(int instanceId, IntPtr msgStrPtr); + public delegate void OnErrorCallback(int instanceId, IntPtr errorPtr); + public delegate void OnCloseCallback(int instanceId, int closeCode, IntPtr reasonPtr); + + /* WebSocket JSLIB functions */ + [DllImport("__Internal")] + public static extern int WebSocketConnect(int instanceId); + + [DllImport("__Internal")] + public static extern int WebSocketClose(int instanceId, int code, string reason); + + [DllImport("__Internal")] + public static extern int WebSocketSend(int instanceId, byte[] dataPtr, int offset,int dataLength); + + [DllImport("__Internal")] + public static extern int WebSocketSendStr(int instanceId, string data); + + [DllImport("__Internal")] + public static extern int WebSocketGetState(int instanceId); + + /* WebSocket JSLIB callback setters and other functions */ + [DllImport("__Internal")] + public static extern int WebSocketAllocate(string url); + + [DllImport("__Internal")] + public static extern int WebSocketAddSubProtocol(int instanceId, string protocol); + + [DllImport("__Internal")] + public static extern void WebSocketFree(int instanceId); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnOpen(OnOpenCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnMessage(OnMessageCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnMessageStr(OnMessageStrCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnError(OnErrorCallback callback); + + [DllImport("__Internal")] + public static extern void WebSocketSetOnClose(OnCloseCallback callback); + + /* If callbacks was initialized and set */ + private static bool isInitialized = false; + + /* Initialize WebSocket callbacks to JSLIB */ + private static void Initialize() + { + WebSocketSetOnOpen(DelegateOnOpenEvent); + WebSocketSetOnMessage(DelegateOnMessageEvent); + WebSocketSetOnMessageStr(DelegateOnMessageStrEvent); + WebSocketSetOnError(DelegateOnErrorEvent); + WebSocketSetOnClose(DelegateOnCloseEvent); + + isInitialized = true; + } + + [MonoPInvokeCallback(typeof(OnOpenCallback))] + public static void DelegateOnOpenEvent(int instanceId) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + socket.HandleOnOpen(); + } + } + + [MonoPInvokeCallback(typeof(OnMessageCallback))] + public static void DelegateOnMessageEvent(int instanceId, IntPtr msgPtr, int msgSize) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + var bytes = new byte[msgSize]; + Marshal.Copy(msgPtr, bytes, 0, msgSize); + socket.HandleOnMessage(bytes); + } + } + + [MonoPInvokeCallback(typeof(OnMessageStrCallback))] + public static void DelegateOnMessageStrEvent(int instanceId, IntPtr msgStrPtr) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + string msgStr = Marshal.PtrToStringAuto(msgStrPtr); + socket.HandleOnMessageStr(msgStr); + } + } + + [MonoPInvokeCallback(typeof(OnErrorCallback))] + public static void DelegateOnErrorEvent(int instanceId, IntPtr errorPtr) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + string errorMsg = Marshal.PtrToStringAuto(errorPtr); + socket.HandleOnError(errorMsg); + } + } + + [MonoPInvokeCallback(typeof(OnCloseCallback))] + public static void DelegateOnCloseEvent(int instanceId, int closeCode, IntPtr reasonPtr) + { + if (sockets.TryGetValue(instanceId, out var socket)) + { + string reason = Marshal.PtrToStringAuto(reasonPtr); + socket.HandleOnClose((ushort)closeCode, reason); + } + } + + internal static int AllocateInstance(string address) + { + if (!isInitialized) Initialize(); + return WebSocketAllocate(address); + } + + internal static void Add(WebSocket socket) + { + if (!sockets.ContainsKey(socket.instanceId)) + { + sockets.Add(socket.instanceId, socket); + } + } + + internal static void Remove(int instanceId) + { + if (sockets.ContainsKey(instanceId)) + { + sockets.Remove(instanceId); + } + } + } +} +#endif diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta new file mode 100644 index 00000000..d0a16fef --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WSocket/Implementation/WebGL/WebSocketManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 246cdc66a1e2047148371a8e56e17d3a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL.meta new file mode 100644 index 00000000..404a7f6b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f1a1a6aea65cc413faf8fb4421138b29 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL/WebSocket.jslib b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL/WebSocket.jslib new file mode 100644 index 00000000..578c7ee1 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL/WebSocket.jslib @@ -0,0 +1,338 @@ +var WebSocketLibrary = +{ + $webSocketManager: + { + /* + * Map of instances + * + * Instance structure: + * { + * url: string, + * ws: WebSocket, + * subProtocols: string[], + * } + */ + instances: {}, + + /* Last instance ID */ + lastId: 0, + + /* Event listeners */ + onOpen: null, + onMessage: null, + onMessageStr: null, + onError: null, + onClose: null + }, + + /** + * Set onOpen callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnOpen: function(callback) + { + webSocketManager.onOpen = callback; + }, + + /** + * Set onMessage callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnMessage: function(callback) + { + webSocketManager.onMessage = callback; + }, + + /** + * Set onMessageStr callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnMessageStr: function(callback) + { + webSocketManager.onMessageStr = callback; + }, + + /** + * Set onError callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnError: function(callback) + { + webSocketManager.onError = callback; + }, + + /** + * Set onClose callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnClose: function(callback) + { + webSocketManager.onClose = callback; + }, + + /** + * Allocate new WebSocket instance struct + * + * @param url Server URL + */ + WebSocketAllocate: function(urlPtr) + { + var url = UTF8ToString(urlPtr); + var id = ++webSocketManager.lastId; + webSocketManager.instances[id] = { + url: url, + ws: null, + }; + + return id; + }, + + /** + * Add Sub Protocol + * + * @param instanceId Instance ID + * @param protocol Sub Protocol + */ + WebSocketAddSubProtocol: function(instanceId, protocolPtr) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + + var protocol = UTF8ToString(protocolPtr); + + if (instance.subProtocols == null) + instance.subProtocols = []; + + instance.subProtocols.push(protocol); + + return 0; + }, + + /** + * Remove reference to WebSocket instance + * + * If socket is not closed function will close it but onClose event will not be emitted because + * this function should be invoked by C# WebSocket destructor. + * + * @param instanceId Instance ID + */ + WebSocketFree: function(instanceId) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return 0; + + // Close if not closed + if (instance.ws !== null && instance.ws.readyState < 2) + instance.ws.close(); + + // Remove reference + delete webSocketManager.instances[instanceId]; + + return 0; + }, + + /** + * Connect WebSocket to the server + * + * @param instanceId Instance ID + */ + WebSocketConnect: function(instanceId) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws !== null) return -2; + + if (instance.subProtocols != null) + instance.ws = new WebSocket(instance.url, instance.subProtocols); + else + instance.ws = new WebSocket(instance.url); + + instance.ws.onopen = function() + { + Module.dynCall_vi(webSocketManager.onOpen, instanceId); + }; + + instance.ws.onmessage = function(ev) + { + if (ev.data instanceof ArrayBuffer) + { + var array = new Uint8Array(ev.data); + var buffer = _malloc(array.length); + writeArrayToMemory(array, buffer); + try + { + Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, array.length); + } + finally + { + _free(buffer); + } + } + else if (typeof ev.data == 'string') + { + var length = lengthBytesUTF8(ev.data) + 1; + var buffer = _malloc(length); + stringToUTF8(ev.data, buffer, length); + try + { + Module.dynCall_vii(webSocketManager.onMessageStr, instanceId, buffer); + } + finally + { + _free(buffer); + } + } + else if (typeof Blob !== 'undefined' && ev.data instanceof Blob) + { + var reader = new FileReader(); + reader.onload = function() + { + var array = new Uint8Array(reader.result); + var buffer = _malloc(array.length); + writeArrayToMemory(array, buffer); + try + { + Module.dynCall_viii(webSocketManager.onMessage, instanceId, buffer, array.length); + } + finally + { + reader = null; + _free(buffer); + } + }; + reader.readAsArrayBuffer(ev.data); + } + else + { + console.log("[JSLIB WebSocket] not support message type: ", (typeof ev.data)); + } + }; + + instance.ws.onerror = function(ev) + { + var msg = "WebSocket error."; + var length = lengthBytesUTF8(msg) + 1; + var buffer = _malloc(length); + stringToUTF8(msg, buffer, length); + try + { + Module.dynCall_vii(webSocketManager.onError, instanceId, buffer); + } + finally + { + _free(buffer); + } + }; + + instance.ws.onclose = function(ev) + { + var msg = ev.reason; + var length = lengthBytesUTF8(msg) + 1; + var buffer = _malloc(length); + stringToUTF8(msg, buffer, length); + try + { + Module.dynCall_viii(webSocketManager.onClose, instanceId, ev.code, buffer); + } + finally + { + _free(buffer); + } + instance.ws = null; + }; + + return 0; + }, + + /** + * Close WebSocket connection + * + * @param instanceId Instance ID + * @param code Close status code + * @param reasonPtr Pointer to reason string + */ + WebSocketClose: function(instanceId, code, reasonPtr) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return -3; + if (instance.ws.readyState === 2) return -4; + if (instance.ws.readyState === 3) return -5; + + var reason = ( reasonPtr ? UTF8ToString(reasonPtr) : undefined ); + try + { + instance.ws.close(code, reason); + } + catch (err) + { + return -7; + } + + return 0; + }, + + /** + * Send message over WebSocket + * + * @param instanceId Instance ID + * @param bufferPtr Pointer to the message buffer + * @param length Length of the message in the buffer + */ + WebSocketSend: function(instanceId, bufferPtr, offset, length) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return -3; + if (instance.ws.readyState !== 1) return -6; + + if (typeof HEAPU8 !== 'undefined') + instance.ws.send(HEAPU8.buffer.slice(bufferPtr + offset, bufferPtr + length)); + else if (typeof buffer !== 'undefined') + instance.ws.send(buffer.slice(bufferPtr + offset, bufferPtr + length)); + else + return -8; // not support buffer slice + + return 0; + }, + + /** + * Send message string over WebSocket + * + * @param instanceId Instance ID + * @param stringPtr Pointer to the message string + */ + WebSocketSendStr: function(instanceId, stringPtr) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return -3; + if (instance.ws.readyState !== 1) return -6; + + instance.ws.send(UTF8ToString(stringPtr)); + + return 0; + }, + + /** + * Return WebSocket readyState + * + * @param instanceId Instance ID + */ + WebSocketGetState: function(instanceId) + { + var instance = webSocketManager.instances[instanceId]; + if (!instance) return -1; + if (instance.ws === null) return 3; // socket null as closed + + return instance.ws.readyState; + } +}; + +autoAddDeps(WebSocketLibrary, '$webSocketManager'); +mergeInto(LibraryManager.library, WebSocketLibrary); diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL/WebSocket.jslib.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL/WebSocket.jslib.meta new file mode 100644 index 00000000..0d3f5887 --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/Runtime/Plugins/WebGL/WebSocket.jslib.meta @@ -0,0 +1,42 @@ +fileFormatVersion: 2 +guid: bd88770aa13fc47b08f87d2145e9ac6e +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: + Facebook: WebGL + second: + enabled: 1 + settings: {} + - first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + - first: + WeixinMiniGame: WeixinMiniGame + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/csc.rsp b/Fantasy.Unity/Fantasy.Unity.UniTask/csc.rsp new file mode 100644 index 00000000..5144b19a --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/csc.rsp @@ -0,0 +1 @@ +-define:FANTASY_UNITY \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/csc.rsp.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/csc.rsp.meta new file mode 100644 index 00000000..37b5f8eb --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/csc.rsp.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 839059bf7dc694c46b95d545f4de03c9 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/package.json b/Fantasy.Unity/Fantasy.Unity.UniTask/package.json new file mode 100644 index 00000000..c5e01f6b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/package.json @@ -0,0 +1,25 @@ +{ + "name": "com.fantasy.unity", + "version": "2024.1.14", + "displayName": "Fantasy.Unity.UniTask", + "description": "Fantasy is a cross platform distributed server framework.", + "category": "Network Framework", + "documentationUrl": "https://www.code-fantasy.com/", + "changelogUrl": "https://www.code-fantasy.com/", + "licensesUrl": "https://www.code-fantasy.com/", + "keywords": [ + "Fantasy", + "Framework", + "hotfix", + "Server", + "Network" + ], + "author": { + "name": "Fantasy", + "email": "362946@qq.com", + "url": "https://www.code-fantasy.com/" + }, + "dependencies": { + "com.unity.nuget.newtonsoft-json": "3.2.1" + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Fantasy.Unity.UniTask/package.json.meta b/Fantasy.Unity/Fantasy.Unity.UniTask/package.json.meta new file mode 100644 index 00000000..fa5a5c1b --- /dev/null +++ b/Fantasy.Unity/Fantasy.Unity.UniTask/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: e2fcc306250504c38a18e633f5118933 +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask.meta b/Fantasy.Unity/Plugins/UniTask.meta new file mode 100644 index 00000000..fd206f13 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 091d462f43828284f859548352640f6d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Editor.meta b/Fantasy.Unity/Plugins/UniTask/Editor.meta new file mode 100644 index 00000000..366a9a6d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 564f440f9b25da9479be7487598be72e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/SplitterGUILayout.cs b/Fantasy.Unity/Plugins/UniTask/Editor/SplitterGUILayout.cs new file mode 100644 index 00000000..41891337 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/SplitterGUILayout.cs @@ -0,0 +1,62 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Editor +{ + // reflection call of UnityEditor.SplitterGUILayout + internal static class SplitterGUILayout + { + static BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + + static Lazy splitterStateType = new Lazy(() => + { + var type = typeof(EditorWindow).Assembly.GetTypes().First(x => x.FullName == "UnityEditor.SplitterState"); + return type; + }); + + static Lazy splitterStateCtor = new Lazy(() => + { + var type = splitterStateType.Value; + return type.GetConstructor(flags, null, new Type[] { typeof(float[]), typeof(int[]), typeof(int[]) }, null); + }); + + static Lazy splitterGUILayoutType = new Lazy(() => + { + var type = typeof(EditorWindow).Assembly.GetTypes().First(x => x.FullName == "UnityEditor.SplitterGUILayout"); + return type; + }); + + static Lazy beginVerticalSplit = new Lazy(() => + { + var type = splitterGUILayoutType.Value; + return type.GetMethod("BeginVerticalSplit", flags, null, new Type[] { splitterStateType.Value, typeof(GUILayoutOption[]) }, null); + }); + + static Lazy endVerticalSplit = new Lazy(() => + { + var type = splitterGUILayoutType.Value; + return type.GetMethod("EndVerticalSplit", flags, null, Type.EmptyTypes, null); + }); + + public static object CreateSplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes) + { + return splitterStateCtor.Value.Invoke(new object[] { relativeSizes, minSizes, maxSizes }); + } + + public static void BeginVerticalSplit(object splitterState, params GUILayoutOption[] options) + { + beginVerticalSplit.Value.Invoke(null, new object[] { splitterState, options }); + } + + public static void EndVerticalSplit() + { + endVerticalSplit.Value.Invoke(null, Type.EmptyTypes); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/SplitterGUILayout.cs.meta b/Fantasy.Unity/Plugins/UniTask/Editor/SplitterGUILayout.cs.meta new file mode 100644 index 00000000..4d718f4e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/SplitterGUILayout.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 40ef2e46f900131419e869398a8d3c9d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/UniTask.Editor.asmdef b/Fantasy.Unity/Plugins/UniTask/Editor/UniTask.Editor.asmdef new file mode 100644 index 00000000..c618c6ac --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/UniTask.Editor.asmdef @@ -0,0 +1,17 @@ +{ + "name": "UniTask.Editor", + "references": [ + "UniTask" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": false, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/UniTask.Editor.asmdef.meta b/Fantasy.Unity/Plugins/UniTask/Editor/UniTask.Editor.asmdef.meta new file mode 100644 index 00000000..821b87b7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/UniTask.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4129704b5a1a13841ba16f230bf24a57 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerTreeView.cs b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerTreeView.cs new file mode 100644 index 00000000..e7b62692 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerTreeView.cs @@ -0,0 +1,182 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System; +using UnityEditor.IMGUI.Controls; +using Cysharp.Threading.Tasks.Internal; +using System.Text; +using System.Text.RegularExpressions; + +namespace Cysharp.Threading.Tasks.Editor +{ + public class UniTaskTrackerViewItem : TreeViewItem + { + static Regex removeHref = new Regex("(.+)", RegexOptions.Compiled); + + public string TaskType { get; set; } + public string Elapsed { get; set; } + public string Status { get; set; } + + string position; + public string Position + { + get { return position; } + set + { + position = value; + PositionFirstLine = GetFirstLine(position); + } + } + + public string PositionFirstLine { get; private set; } + + static string GetFirstLine(string str) + { + var sb = new StringBuilder(); + for (int i = 0; i < str.Length; i++) + { + if (str[i] == '\r' || str[i] == '\n') + { + break; + } + sb.Append(str[i]); + } + + return removeHref.Replace(sb.ToString(), "$1"); + } + + public UniTaskTrackerViewItem(int id) : base(id) + { + + } + } + + public class UniTaskTrackerTreeView : TreeView + { + const string sortedColumnIndexStateKey = "UniTaskTrackerTreeView_sortedColumnIndex"; + + public IReadOnlyList CurrentBindingItems; + + public UniTaskTrackerTreeView() + : this(new TreeViewState(), new MultiColumnHeader(new MultiColumnHeaderState(new[] + { + new MultiColumnHeaderState.Column() { headerContent = new GUIContent("TaskType"), width = 20}, + new MultiColumnHeaderState.Column() { headerContent = new GUIContent("Elapsed"), width = 10}, + new MultiColumnHeaderState.Column() { headerContent = new GUIContent("Status"), width = 10}, + new MultiColumnHeaderState.Column() { headerContent = new GUIContent("Position")}, + }))) + { + } + + UniTaskTrackerTreeView(TreeViewState state, MultiColumnHeader header) + : base(state, header) + { + rowHeight = 20; + showAlternatingRowBackgrounds = true; + showBorder = true; + header.sortingChanged += Header_sortingChanged; + + header.ResizeToFit(); + Reload(); + + header.sortedColumnIndex = SessionState.GetInt(sortedColumnIndexStateKey, 1); + } + + public void ReloadAndSort() + { + var currentSelected = this.state.selectedIDs; + Reload(); + Header_sortingChanged(this.multiColumnHeader); + this.state.selectedIDs = currentSelected; + } + + private void Header_sortingChanged(MultiColumnHeader multiColumnHeader) + { + SessionState.SetInt(sortedColumnIndexStateKey, multiColumnHeader.sortedColumnIndex); + var index = multiColumnHeader.sortedColumnIndex; + var ascending = multiColumnHeader.IsSortedAscending(multiColumnHeader.sortedColumnIndex); + + var items = rootItem.children.Cast(); + + IOrderedEnumerable orderedEnumerable; + switch (index) + { + case 0: + orderedEnumerable = ascending ? items.OrderBy(item => item.TaskType) : items.OrderByDescending(item => item.TaskType); + break; + case 1: + orderedEnumerable = ascending ? items.OrderBy(item => double.Parse(item.Elapsed)) : items.OrderByDescending(item => double.Parse(item.Elapsed)); + break; + case 2: + orderedEnumerable = ascending ? items.OrderBy(item => item.Status) : items.OrderByDescending(item => item.Elapsed); + break; + case 3: + orderedEnumerable = ascending ? items.OrderBy(item => item.Position) : items.OrderByDescending(item => item.PositionFirstLine); + break; + default: + throw new ArgumentOutOfRangeException(nameof(index), index, null); + } + + CurrentBindingItems = rootItem.children = orderedEnumerable.Cast().ToList(); + BuildRows(rootItem); + } + + protected override TreeViewItem BuildRoot() + { + var root = new TreeViewItem { depth = -1 }; + + var children = new List(); + + TaskTracker.ForEachActiveTask((trackingId, awaiterType, status, created, stackTrace) => + { + children.Add(new UniTaskTrackerViewItem(trackingId) { TaskType = awaiterType, Status = status.ToString(), Elapsed = (DateTime.UtcNow - created).TotalSeconds.ToString("00.00"), Position = stackTrace }); + }); + + CurrentBindingItems = children; + root.children = CurrentBindingItems as List; + return root; + } + + protected override bool CanMultiSelect(TreeViewItem item) + { + return false; + } + + protected override void RowGUI(RowGUIArgs args) + { + var item = args.item as UniTaskTrackerViewItem; + + for (var visibleColumnIndex = 0; visibleColumnIndex < args.GetNumVisibleColumns(); visibleColumnIndex++) + { + var rect = args.GetCellRect(visibleColumnIndex); + var columnIndex = args.GetColumn(visibleColumnIndex); + + var labelStyle = args.selected ? EditorStyles.whiteLabel : EditorStyles.label; + labelStyle.alignment = TextAnchor.MiddleLeft; + switch (columnIndex) + { + case 0: + EditorGUI.LabelField(rect, item.TaskType, labelStyle); + break; + case 1: + EditorGUI.LabelField(rect, item.Elapsed, labelStyle); + break; + case 2: + EditorGUI.LabelField(rect, item.Status, labelStyle); + break; + case 3: + EditorGUI.LabelField(rect, item.PositionFirstLine, labelStyle); + break; + default: + throw new ArgumentOutOfRangeException(nameof(columnIndex), columnIndex, null); + } + } + } + } + +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerTreeView.cs.meta b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerTreeView.cs.meta new file mode 100644 index 00000000..9b34d7b9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerTreeView.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 52e2d973a2156674e8c1c9433ed031f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerWindow.cs b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerWindow.cs new file mode 100644 index 00000000..242ac6db --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerWindow.cs @@ -0,0 +1,209 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System; +using UnityEditor.IMGUI.Controls; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Editor +{ + public class UniTaskTrackerWindow : EditorWindow + { + static int interval; + + static UniTaskTrackerWindow window; + + [MenuItem("Window/UniTask Tracker")] + public static void OpenWindow() + { + if (window != null) + { + window.Close(); + } + + // will called OnEnable(singleton instance will be set). + GetWindow("UniTask Tracker").Show(); + } + + static readonly GUILayoutOption[] EmptyLayoutOption = new GUILayoutOption[0]; + + UniTaskTrackerTreeView treeView; + object splitterState; + + void OnEnable() + { + window = this; // set singleton. + splitterState = SplitterGUILayout.CreateSplitterState(new float[] { 75f, 25f }, new int[] { 32, 32 }, null); + treeView = new UniTaskTrackerTreeView(); + TaskTracker.EditorEnableState.EnableAutoReload = EditorPrefs.GetBool(TaskTracker.EnableAutoReloadKey, false); + TaskTracker.EditorEnableState.EnableTracking = EditorPrefs.GetBool(TaskTracker.EnableTrackingKey, false); + TaskTracker.EditorEnableState.EnableStackTrace = EditorPrefs.GetBool(TaskTracker.EnableStackTraceKey, false); + } + + void OnGUI() + { + // Head + RenderHeadPanel(); + + // Splittable + SplitterGUILayout.BeginVerticalSplit(this.splitterState, EmptyLayoutOption); + { + // Column Tabble + RenderTable(); + + // StackTrace details + RenderDetailsPanel(); + } + SplitterGUILayout.EndVerticalSplit(); + } + + #region HeadPanel + + public static bool EnableAutoReload => TaskTracker.EditorEnableState.EnableAutoReload; + public static bool EnableTracking => TaskTracker.EditorEnableState.EnableTracking; + public static bool EnableStackTrace => TaskTracker.EditorEnableState.EnableStackTrace; + static readonly GUIContent EnableAutoReloadHeadContent = EditorGUIUtility.TrTextContent("Enable AutoReload", "Reload automatically.", (Texture)null); + static readonly GUIContent ReloadHeadContent = EditorGUIUtility.TrTextContent("Reload", "Reload View.", (Texture)null); + static readonly GUIContent GCHeadContent = EditorGUIUtility.TrTextContent("GC.Collect", "Invoke GC.Collect.", (Texture)null); + static readonly GUIContent EnableTrackingHeadContent = EditorGUIUtility.TrTextContent("Enable Tracking", "Start to track async/await UniTask. Performance impact: low", (Texture)null); + static readonly GUIContent EnableStackTraceHeadContent = EditorGUIUtility.TrTextContent("Enable StackTrace", "Capture StackTrace when task is started. Performance impact: high", (Texture)null); + + // [Enable Tracking] | [Enable StackTrace] + void RenderHeadPanel() + { + EditorGUILayout.BeginVertical(EmptyLayoutOption); + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, EmptyLayoutOption); + + if (GUILayout.Toggle(EnableAutoReload, EnableAutoReloadHeadContent, EditorStyles.toolbarButton, EmptyLayoutOption) != EnableAutoReload) + { + TaskTracker.EditorEnableState.EnableAutoReload = !EnableAutoReload; + } + + if (GUILayout.Toggle(EnableTracking, EnableTrackingHeadContent, EditorStyles.toolbarButton, EmptyLayoutOption) != EnableTracking) + { + TaskTracker.EditorEnableState.EnableTracking = !EnableTracking; + } + + if (GUILayout.Toggle(EnableStackTrace, EnableStackTraceHeadContent, EditorStyles.toolbarButton, EmptyLayoutOption) != EnableStackTrace) + { + TaskTracker.EditorEnableState.EnableStackTrace = !EnableStackTrace; + } + + GUILayout.FlexibleSpace(); + + if (GUILayout.Button(ReloadHeadContent, EditorStyles.toolbarButton, EmptyLayoutOption)) + { + TaskTracker.CheckAndResetDirty(); + treeView.ReloadAndSort(); + Repaint(); + } + + if (GUILayout.Button(GCHeadContent, EditorStyles.toolbarButton, EmptyLayoutOption)) + { + GC.Collect(0); + } + + EditorGUILayout.EndHorizontal(); + EditorGUILayout.EndVertical(); + } + + #endregion + + #region TableColumn + + Vector2 tableScroll; + GUIStyle tableListStyle; + + void RenderTable() + { + if (tableListStyle == null) + { + tableListStyle = new GUIStyle("CN Box"); + tableListStyle.margin.top = 0; + tableListStyle.padding.left = 3; + } + + EditorGUILayout.BeginVertical(tableListStyle, EmptyLayoutOption); + + this.tableScroll = EditorGUILayout.BeginScrollView(this.tableScroll, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.MaxWidth(2000f) + }); + var controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.ExpandWidth(true) + }); + + + treeView?.OnGUI(controlRect); + + EditorGUILayout.EndScrollView(); + EditorGUILayout.EndVertical(); + } + + private void Update() + { + if (EnableAutoReload) + { + if (interval++ % 120 == 0) + { + if (TaskTracker.CheckAndResetDirty()) + { + treeView.ReloadAndSort(); + Repaint(); + } + } + } + } + + #endregion + + #region Details + + static GUIStyle detailsStyle; + Vector2 detailsScroll; + + void RenderDetailsPanel() + { + if (detailsStyle == null) + { + detailsStyle = new GUIStyle("CN Message"); + detailsStyle.wordWrap = false; + detailsStyle.stretchHeight = true; + detailsStyle.margin.right = 15; + } + + string message = ""; + var selected = treeView.state.selectedIDs; + if (selected.Count > 0) + { + var first = selected[0]; + var item = treeView.CurrentBindingItems.FirstOrDefault(x => x.id == first) as UniTaskTrackerViewItem; + if (item != null) + { + message = item.Position; + } + } + + detailsScroll = EditorGUILayout.BeginScrollView(this.detailsScroll, EmptyLayoutOption); + var vector = detailsStyle.CalcSize(new GUIContent(message)); + EditorGUILayout.SelectableLabel(message, detailsStyle, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.ExpandWidth(true), + GUILayout.MinWidth(vector.x), + GUILayout.MinHeight(vector.y) + }); + EditorGUILayout.EndScrollView(); + } + + #endregion + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerWindow.cs.meta b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerWindow.cs.meta new file mode 100644 index 00000000..ba1b7045 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Editor/UniTaskTrackerWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5bee3e3860e37484aa3b861bf76d129f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime.meta b/Fantasy.Unity/Plugins/UniTask/Runtime.meta new file mode 100644 index 00000000..c7fd0162 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f73cc7120b24f7a4f878663c23a55591 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncLazy.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncLazy.cs new file mode 100644 index 00000000..51bfadc7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncLazy.cs @@ -0,0 +1,245 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public class AsyncLazy + { + static Action continuation = SetCompletionSource; + + Func taskFactory; + UniTaskCompletionSource completionSource; + UniTask.Awaiter awaiter; + + object syncLock; + bool initialized; + + public AsyncLazy(Func taskFactory) + { + this.taskFactory = taskFactory; + this.completionSource = new UniTaskCompletionSource(); + this.syncLock = new object(); + this.initialized = false; + } + + internal AsyncLazy(UniTask task) + { + this.taskFactory = null; + this.completionSource = new UniTaskCompletionSource(); + this.syncLock = null; + this.initialized = true; + + var awaiter = task.GetAwaiter(); + if (awaiter.IsCompleted) + { + SetCompletionSource(awaiter); + } + else + { + this.awaiter = awaiter; + awaiter.SourceOnCompleted(continuation, this); + } + } + + public UniTask Task + { + get + { + EnsureInitialized(); + return completionSource.Task; + } + } + + + public UniTask.Awaiter GetAwaiter() => Task.GetAwaiter(); + + void EnsureInitialized() + { + if (Volatile.Read(ref initialized)) + { + return; + } + + EnsureInitializedCore(); + } + + void EnsureInitializedCore() + { + lock (syncLock) + { + if (!Volatile.Read(ref initialized)) + { + var f = Interlocked.Exchange(ref taskFactory, null); + if (f != null) + { + var task = f(); + var awaiter = task.GetAwaiter(); + if (awaiter.IsCompleted) + { + SetCompletionSource(awaiter); + } + else + { + this.awaiter = awaiter; + awaiter.SourceOnCompleted(continuation, this); + } + + Volatile.Write(ref initialized, true); + } + } + } + } + + void SetCompletionSource(in UniTask.Awaiter awaiter) + { + try + { + awaiter.GetResult(); + completionSource.TrySetResult(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void SetCompletionSource(object state) + { + var self = (AsyncLazy)state; + try + { + self.awaiter.GetResult(); + self.completionSource.TrySetResult(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + finally + { + self.awaiter = default; + } + } + } + + public class AsyncLazy + { + static Action continuation = SetCompletionSource; + + Func> taskFactory; + UniTaskCompletionSource completionSource; + UniTask.Awaiter awaiter; + + object syncLock; + bool initialized; + + public AsyncLazy(Func> taskFactory) + { + this.taskFactory = taskFactory; + this.completionSource = new UniTaskCompletionSource(); + this.syncLock = new object(); + this.initialized = false; + } + + internal AsyncLazy(UniTask task) + { + this.taskFactory = null; + this.completionSource = new UniTaskCompletionSource(); + this.syncLock = null; + this.initialized = true; + + var awaiter = task.GetAwaiter(); + if (awaiter.IsCompleted) + { + SetCompletionSource(awaiter); + } + else + { + this.awaiter = awaiter; + awaiter.SourceOnCompleted(continuation, this); + } + } + + public UniTask Task + { + get + { + EnsureInitialized(); + return completionSource.Task; + } + } + + + public UniTask.Awaiter GetAwaiter() => Task.GetAwaiter(); + + void EnsureInitialized() + { + if (Volatile.Read(ref initialized)) + { + return; + } + + EnsureInitializedCore(); + } + + void EnsureInitializedCore() + { + lock (syncLock) + { + if (!Volatile.Read(ref initialized)) + { + var f = Interlocked.Exchange(ref taskFactory, null); + if (f != null) + { + var task = f(); + var awaiter = task.GetAwaiter(); + if (awaiter.IsCompleted) + { + SetCompletionSource(awaiter); + } + else + { + this.awaiter = awaiter; + awaiter.SourceOnCompleted(continuation, this); + } + + Volatile.Write(ref initialized, true); + } + } + } + } + + void SetCompletionSource(in UniTask.Awaiter awaiter) + { + try + { + var result = awaiter.GetResult(); + completionSource.TrySetResult(result); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void SetCompletionSource(object state) + { + var self = (AsyncLazy)state; + try + { + var result = self.awaiter.GetResult(); + self.completionSource.TrySetResult(result); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + finally + { + self.awaiter = default; + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncLazy.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncLazy.cs.meta new file mode 100644 index 00000000..554d1628 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncLazy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 01d1404ca421466419a7db7340ff5e77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncReactiveProperty.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncReactiveProperty.cs new file mode 100644 index 00000000..a08844df --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncReactiveProperty.cs @@ -0,0 +1,644 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public interface IReadOnlyAsyncReactiveProperty : IUniTaskAsyncEnumerable + { + T Value { get; } + IUniTaskAsyncEnumerable WithoutCurrent(); + UniTask WaitAsync(CancellationToken cancellationToken = default); + } + + public interface IAsyncReactiveProperty : IReadOnlyAsyncReactiveProperty + { + new T Value { get; set; } + } + + [Serializable] + public class AsyncReactiveProperty : IAsyncReactiveProperty, IDisposable + { + TriggerEvent triggerEvent; + +#if UNITY_2018_3_OR_NEWER + [UnityEngine.SerializeField] +#endif + T latestValue; + + public T Value + { + get + { + return latestValue; + } + set + { + this.latestValue = value; + triggerEvent.SetResult(value); + } + } + + public AsyncReactiveProperty(T value) + { + this.latestValue = value; + this.triggerEvent = default; + } + + public IUniTaskAsyncEnumerable WithoutCurrent() + { + return new WithoutCurrentEnumerable(this); + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken) + { + return new Enumerator(this, cancellationToken, true); + } + + public void Dispose() + { + triggerEvent.SetCompleted(); + } + + public static implicit operator T(AsyncReactiveProperty value) + { + return value.Value; + } + + public override string ToString() + { + if (isValueType) return latestValue.ToString(); + return latestValue?.ToString(); + } + + public UniTask WaitAsync(CancellationToken cancellationToken = default) + { + return new UniTask(WaitAsyncSource.Create(this, cancellationToken, out var token), token); + } + + static bool isValueType; + + static AsyncReactiveProperty() + { + isValueType = typeof(T).IsValueType; + } + + sealed class WaitAsyncSource : IUniTaskSource, ITriggerHandler, ITaskPoolNode + { + static Action cancellationCallback = CancellationCallback; + + static TaskPool pool; + WaitAsyncSource nextNode; + ref WaitAsyncSource ITaskPoolNode.NextNode => ref nextNode; + + static WaitAsyncSource() + { + TaskPool.RegisterSizeGetter(typeof(WaitAsyncSource), () => pool.Size); + } + + AsyncReactiveProperty parent; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + UniTaskCompletionSourceCore core; + + WaitAsyncSource() + { + } + + public static IUniTaskSource Create(AsyncReactiveProperty parent, CancellationToken cancellationToken, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitAsyncSource(); + } + + result.parent = parent; + result.cancellationToken = cancellationToken; + + if (cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, result); + } + + result.parent.triggerEvent.Add(result); + + TaskTracker.TrackActiveTask(result, 3); + + token = result.core.Version; + return result; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + cancellationTokenRegistration.Dispose(); + cancellationTokenRegistration = default; + parent.triggerEvent.Remove(this); + parent = null; + cancellationToken = default; + return pool.TryPush(this); + } + + static void CancellationCallback(object state) + { + var self = (WaitAsyncSource)state; + self.OnCanceled(self.cancellationToken); + } + + // IUniTaskSource + + public T GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + // ITriggerHandler + + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + public void OnCanceled(CancellationToken cancellationToken) + { + core.TrySetCanceled(cancellationToken); + } + + public void OnCompleted() + { + // Complete as Cancel. + core.TrySetCanceled(CancellationToken.None); + } + + public void OnError(Exception ex) + { + core.TrySetException(ex); + } + + public void OnNext(T value) + { + core.TrySetResult(value); + } + } + + sealed class WithoutCurrentEnumerable : IUniTaskAsyncEnumerable + { + readonly AsyncReactiveProperty parent; + + public WithoutCurrentEnumerable(AsyncReactiveProperty parent) + { + this.parent = parent; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(parent, cancellationToken, false); + } + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator, ITriggerHandler + { + static Action cancellationCallback = CancellationCallback; + + readonly AsyncReactiveProperty parent; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + T value; + bool isDisposed; + bool firstCall; + + public Enumerator(AsyncReactiveProperty parent, CancellationToken cancellationToken, bool publishCurrentValue) + { + this.parent = parent; + this.cancellationToken = cancellationToken; + this.firstCall = publishCurrentValue; + + parent.triggerEvent.Add(this); + TaskTracker.TrackActiveTask(this, 3); + + if (cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + } + + public T Current => value; + + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + public UniTask MoveNextAsync() + { + // raise latest value on first call. + if (firstCall) + { + firstCall = false; + value = parent.Value; + return CompletedTasks.True; + } + + completionSource.Reset(); + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + completionSource.TrySetCanceled(cancellationToken); + parent.triggerEvent.Remove(this); + } + return default; + } + + public void OnNext(T value) + { + this.value = value; + completionSource.TrySetResult(true); + } + + public void OnCanceled(CancellationToken cancellationToken) + { + DisposeAsync().Forget(); + } + + public void OnCompleted() + { + completionSource.TrySetResult(false); + } + + public void OnError(Exception ex) + { + completionSource.TrySetException(ex); + } + + static void CancellationCallback(object state) + { + var self = (Enumerator)state; + self.DisposeAsync().Forget(); + } + } + } + + public class ReadOnlyAsyncReactiveProperty : IReadOnlyAsyncReactiveProperty, IDisposable + { + TriggerEvent triggerEvent; + + T latestValue; + IUniTaskAsyncEnumerator enumerator; + + public T Value + { + get + { + return latestValue; + } + } + + public ReadOnlyAsyncReactiveProperty(T initialValue, IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + latestValue = initialValue; + ConsumeEnumerator(source, cancellationToken).Forget(); + } + + public ReadOnlyAsyncReactiveProperty(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + ConsumeEnumerator(source, cancellationToken).Forget(); + } + + async UniTaskVoid ConsumeEnumerator(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await enumerator.MoveNextAsync()) + { + var value = enumerator.Current; + this.latestValue = value; + triggerEvent.SetResult(value); + } + } + finally + { + await enumerator.DisposeAsync(); + enumerator = null; + } + } + + public IUniTaskAsyncEnumerable WithoutCurrent() + { + return new WithoutCurrentEnumerable(this); + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken) + { + return new Enumerator(this, cancellationToken, true); + } + + public void Dispose() + { + if (enumerator != null) + { + enumerator.DisposeAsync().Forget(); + } + + triggerEvent.SetCompleted(); + } + + public static implicit operator T(ReadOnlyAsyncReactiveProperty value) + { + return value.Value; + } + + public override string ToString() + { + if (isValueType) return latestValue.ToString(); + return latestValue?.ToString(); + } + + public UniTask WaitAsync(CancellationToken cancellationToken = default) + { + return new UniTask(WaitAsyncSource.Create(this, cancellationToken, out var token), token); + } + + static bool isValueType; + + static ReadOnlyAsyncReactiveProperty() + { + isValueType = typeof(T).IsValueType; + } + + sealed class WaitAsyncSource : IUniTaskSource, ITriggerHandler, ITaskPoolNode + { + static Action cancellationCallback = CancellationCallback; + + static TaskPool pool; + WaitAsyncSource nextNode; + ref WaitAsyncSource ITaskPoolNode.NextNode => ref nextNode; + + static WaitAsyncSource() + { + TaskPool.RegisterSizeGetter(typeof(WaitAsyncSource), () => pool.Size); + } + + ReadOnlyAsyncReactiveProperty parent; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + UniTaskCompletionSourceCore core; + + WaitAsyncSource() + { + } + + public static IUniTaskSource Create(ReadOnlyAsyncReactiveProperty parent, CancellationToken cancellationToken, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitAsyncSource(); + } + + result.parent = parent; + result.cancellationToken = cancellationToken; + + if (cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, result); + } + + result.parent.triggerEvent.Add(result); + + TaskTracker.TrackActiveTask(result, 3); + + token = result.core.Version; + return result; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + cancellationTokenRegistration.Dispose(); + cancellationTokenRegistration = default; + parent.triggerEvent.Remove(this); + parent = null; + cancellationToken = default; + return pool.TryPush(this); + } + + static void CancellationCallback(object state) + { + var self = (WaitAsyncSource)state; + self.OnCanceled(self.cancellationToken); + } + + // IUniTaskSource + + public T GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + // ITriggerHandler + + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + public void OnCanceled(CancellationToken cancellationToken) + { + core.TrySetCanceled(cancellationToken); + } + + public void OnCompleted() + { + // Complete as Cancel. + core.TrySetCanceled(CancellationToken.None); + } + + public void OnError(Exception ex) + { + core.TrySetException(ex); + } + + public void OnNext(T value) + { + core.TrySetResult(value); + } + } + + sealed class WithoutCurrentEnumerable : IUniTaskAsyncEnumerable + { + readonly ReadOnlyAsyncReactiveProperty parent; + + public WithoutCurrentEnumerable(ReadOnlyAsyncReactiveProperty parent) + { + this.parent = parent; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(parent, cancellationToken, false); + } + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator, ITriggerHandler + { + static Action cancellationCallback = CancellationCallback; + + readonly ReadOnlyAsyncReactiveProperty parent; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + T value; + bool isDisposed; + bool firstCall; + + public Enumerator(ReadOnlyAsyncReactiveProperty parent, CancellationToken cancellationToken, bool publishCurrentValue) + { + this.parent = parent; + this.cancellationToken = cancellationToken; + this.firstCall = publishCurrentValue; + + parent.triggerEvent.Add(this); + TaskTracker.TrackActiveTask(this, 3); + + if (cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + } + + public T Current => value; + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + public UniTask MoveNextAsync() + { + // raise latest value on first call. + if (firstCall) + { + firstCall = false; + value = parent.Value; + return CompletedTasks.True; + } + + completionSource.Reset(); + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + completionSource.TrySetCanceled(cancellationToken); + parent.triggerEvent.Remove(this); + } + return default; + } + + public void OnNext(T value) + { + this.value = value; + completionSource.TrySetResult(true); + } + + public void OnCanceled(CancellationToken cancellationToken) + { + DisposeAsync().Forget(); + } + + public void OnCompleted() + { + completionSource.TrySetResult(false); + } + + public void OnError(Exception ex) + { + completionSource.TrySetException(ex); + } + + static void CancellationCallback(object state) + { + var self = (Enumerator)state; + self.DisposeAsync().Forget(); + } + } + } + + public static class StateExtensions + { + public static ReadOnlyAsyncReactiveProperty ToReadOnlyAsyncReactiveProperty(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + return new ReadOnlyAsyncReactiveProperty(source, cancellationToken); + } + + public static ReadOnlyAsyncReactiveProperty ToReadOnlyAsyncReactiveProperty(this IUniTaskAsyncEnumerable source, T initialValue, CancellationToken cancellationToken) + { + return new ReadOnlyAsyncReactiveProperty(initialValue, source, cancellationToken); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncReactiveProperty.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncReactiveProperty.cs.meta new file mode 100644 index 00000000..d64e3cff --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncReactiveProperty.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ef320b87f537ee4fb2282e765dc6166 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncUnit.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncUnit.cs new file mode 100644 index 00000000..1d4bc742 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncUnit.cs @@ -0,0 +1,26 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or + +using System; + +namespace Cysharp.Threading.Tasks +{ + public readonly struct AsyncUnit : IEquatable + { + public static readonly AsyncUnit Default = new AsyncUnit(); + + public override int GetHashCode() + { + return 0; + } + + public bool Equals(AsyncUnit other) + { + return true; + } + + public override string ToString() + { + return "()"; + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncUnit.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncUnit.cs.meta new file mode 100644 index 00000000..e0ee1329 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/AsyncUnit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f95ac245430d304bb5128d13b6becc8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenEqualityComparer.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenEqualityComparer.cs new file mode 100644 index 00000000..42e94451 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenEqualityComparer.cs @@ -0,0 +1,23 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public class CancellationTokenEqualityComparer : IEqualityComparer + { + public static readonly IEqualityComparer Default = new CancellationTokenEqualityComparer(); + + public bool Equals(CancellationToken x, CancellationToken y) + { + return x.Equals(y); + } + + public int GetHashCode(CancellationToken obj) + { + return obj.GetHashCode(); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenEqualityComparer.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenEqualityComparer.cs.meta new file mode 100644 index 00000000..a4fe3fd9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenEqualityComparer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d739f510b125b74fa7290ac4335e46e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs new file mode 100644 index 00000000..3f3a532a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs @@ -0,0 +1,182 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public static class CancellationTokenExtensions + { + static readonly Action cancellationTokenCallback = Callback; + static readonly Action disposeCallback = DisposeCallback; + + public static CancellationToken ToCancellationToken(this UniTask task) + { + var cts = new CancellationTokenSource(); + ToCancellationTokenCore(task, cts).Forget(); + return cts.Token; + } + + public static CancellationToken ToCancellationToken(this UniTask task, CancellationToken linkToken) + { + if (linkToken.IsCancellationRequested) + { + return linkToken; + } + + if (!linkToken.CanBeCanceled) + { + return ToCancellationToken(task); + } + + var cts = CancellationTokenSource.CreateLinkedTokenSource(linkToken); + ToCancellationTokenCore(task, cts).Forget(); + + return cts.Token; + } + + public static CancellationToken ToCancellationToken(this UniTask task) + { + return ToCancellationToken(task.AsUniTask()); + } + + public static CancellationToken ToCancellationToken(this UniTask task, CancellationToken linkToken) + { + return ToCancellationToken(task.AsUniTask(), linkToken); + } + + static async UniTaskVoid ToCancellationTokenCore(UniTask task, CancellationTokenSource cts) + { + try + { + await task; + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + cts.Cancel(); + cts.Dispose(); + } + + public static (UniTask, CancellationTokenRegistration) ToUniTask(this CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return (UniTask.FromCanceled(cancellationToken), default(CancellationTokenRegistration)); + } + + var promise = new UniTaskCompletionSource(); + return (promise.Task, cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationTokenCallback, promise)); + } + + static void Callback(object state) + { + var promise = (UniTaskCompletionSource)state; + promise.TrySetResult(); + } + + public static CancellationTokenAwaitable WaitUntilCanceled(this CancellationToken cancellationToken) + { + return new CancellationTokenAwaitable(cancellationToken); + } + + public static CancellationTokenRegistration RegisterWithoutCaptureExecutionContext(this CancellationToken cancellationToken, Action callback) + { + var restoreFlow = false; + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + try + { + return cancellationToken.Register(callback, false); + } + finally + { + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } + } + + public static CancellationTokenRegistration RegisterWithoutCaptureExecutionContext(this CancellationToken cancellationToken, Action callback, object state) + { + var restoreFlow = false; + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + try + { + return cancellationToken.Register(callback, state, false); + } + finally + { + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } + } + + public static CancellationTokenRegistration AddTo(this IDisposable disposable, CancellationToken cancellationToken) + { + return cancellationToken.RegisterWithoutCaptureExecutionContext(disposeCallback, disposable); + } + + static void DisposeCallback(object state) + { + var d = (IDisposable)state; + d.Dispose(); + } + } + + public struct CancellationTokenAwaitable + { + CancellationToken cancellationToken; + + public CancellationTokenAwaitable(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public Awaiter GetAwaiter() + { + return new Awaiter(cancellationToken); + } + + public struct Awaiter : ICriticalNotifyCompletion + { + CancellationToken cancellationToken; + + public Awaiter(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public bool IsCompleted => !cancellationToken.CanBeCanceled || cancellationToken.IsCancellationRequested; + + public void GetResult() + { + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + cancellationToken.RegisterWithoutCaptureExecutionContext(continuation); + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs.meta new file mode 100644 index 00000000..28a69586 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4be7209f04146bd45ac5ee775a5f7c26 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs new file mode 100644 index 00000000..c5199444 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs @@ -0,0 +1,44 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Threading; +using UnityEngine; +using Cysharp.Threading.Tasks.Triggers; +using System; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + + public static partial class CancellationTokenSourceExtensions + { + readonly static Action CancelCancellationTokenSourceStateDelegate = new Action(CancelCancellationTokenSourceState); + + static void CancelCancellationTokenSourceState(object state) + { + var cts = (CancellationTokenSource)state; + cts.Cancel(); + } + + public static IDisposable CancelAfterSlim(this CancellationTokenSource cts, int millisecondsDelay, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) + { + return CancelAfterSlim(cts, TimeSpan.FromMilliseconds(millisecondsDelay), delayType, delayTiming); + } + + public static IDisposable CancelAfterSlim(this CancellationTokenSource cts, TimeSpan delayTimeSpan, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) + { + return PlayerLoopTimer.StartNew(delayTimeSpan, false, delayType, delayTiming, cts.Token, CancelCancellationTokenSourceStateDelegate, cts); + } + + public static void RegisterRaiseCancelOnDestroy(this CancellationTokenSource cts, Component component) + { + RegisterRaiseCancelOnDestroy(cts, component.gameObject); + } + + public static void RegisterRaiseCancelOnDestroy(this CancellationTokenSource cts, GameObject gameObject) + { + var trigger = gameObject.GetAsyncDestroyTrigger(); + trigger.CancellationToken.RegisterWithoutCaptureExecutionContext(CancelCancellationTokenSourceStateDelegate, cts); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs.meta new file mode 100644 index 00000000..fd09fe4b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CancellationTokenSourceExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22d85d07f1e70ab42a7a4c25bd65e661 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Channel.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Channel.cs new file mode 100644 index 00000000..5a484fdc --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Channel.cs @@ -0,0 +1,450 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public static class Channel + { + public static Channel CreateSingleConsumerUnbounded() + { + return new SingleConsumerUnboundedChannel(); + } + } + + public abstract class Channel + { + public ChannelReader Reader { get; protected set; } + public ChannelWriter Writer { get; protected set; } + + public static implicit operator ChannelReader(Channel channel) => channel.Reader; + public static implicit operator ChannelWriter(Channel channel) => channel.Writer; + } + + public abstract class Channel : Channel + { + } + + public abstract class ChannelReader + { + public abstract bool TryRead(out T item); + public abstract UniTask WaitToReadAsync(CancellationToken cancellationToken = default(CancellationToken)); + + public abstract UniTask Completion { get; } + + public virtual UniTask ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) + { + if (this.TryRead(out var item)) + { + return UniTask.FromResult(item); + } + + return ReadAsyncCore(cancellationToken); + } + + async UniTask ReadAsyncCore(CancellationToken cancellationToken = default(CancellationToken)) + { + if (await WaitToReadAsync(cancellationToken)) + { + if (TryRead(out var item)) + { + return item; + } + } + + throw new ChannelClosedException(); + } + + public abstract IUniTaskAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken = default(CancellationToken)); + } + + public abstract class ChannelWriter + { + public abstract bool TryWrite(T item); + public abstract bool TryComplete(Exception error = null); + + public void Complete(Exception error = null) + { + if (!TryComplete(error)) + { + throw new ChannelClosedException(); + } + } + } + + public partial class ChannelClosedException : InvalidOperationException + { + public ChannelClosedException() : + base("Channel is already closed.") + { } + + public ChannelClosedException(string message) : base(message) { } + + public ChannelClosedException(Exception innerException) : + base("Channel is already closed", innerException) + { } + + public ChannelClosedException(string message, Exception innerException) : base(message, innerException) { } + } + + internal class SingleConsumerUnboundedChannel : Channel + { + readonly Queue items; + readonly SingleConsumerUnboundedChannelReader readerSource; + UniTaskCompletionSource completedTaskSource; + UniTask completedTask; + + Exception completionError; + bool closed; + + public SingleConsumerUnboundedChannel() + { + items = new Queue(); + Writer = new SingleConsumerUnboundedChannelWriter(this); + readerSource = new SingleConsumerUnboundedChannelReader(this); + Reader = readerSource; + } + + sealed class SingleConsumerUnboundedChannelWriter : ChannelWriter + { + readonly SingleConsumerUnboundedChannel parent; + + public SingleConsumerUnboundedChannelWriter(SingleConsumerUnboundedChannel parent) + { + this.parent = parent; + } + + public override bool TryWrite(T item) + { + bool waiting; + lock (parent.items) + { + if (parent.closed) return false; + + parent.items.Enqueue(item); + waiting = parent.readerSource.isWaiting; + } + + if (waiting) + { + parent.readerSource.SingalContinuation(); + } + + return true; + } + + public override bool TryComplete(Exception error = null) + { + bool waiting; + lock (parent.items) + { + if (parent.closed) return false; + parent.closed = true; + waiting = parent.readerSource.isWaiting; + + if (parent.items.Count == 0) + { + if (error == null) + { + if (parent.completedTaskSource != null) + { + parent.completedTaskSource.TrySetResult(); + } + else + { + parent.completedTask = UniTask.CompletedTask; + } + } + else + { + if (parent.completedTaskSource != null) + { + parent.completedTaskSource.TrySetException(error); + } + else + { + parent.completedTask = UniTask.FromException(error); + } + } + + if (waiting) + { + parent.readerSource.SingalCompleted(error); + } + } + + parent.completionError = error; + } + + return true; + } + } + + sealed class SingleConsumerUnboundedChannelReader : ChannelReader, IUniTaskSource + { + readonly Action CancellationCallbackDelegate = CancellationCallback; + readonly SingleConsumerUnboundedChannel parent; + + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + UniTaskCompletionSourceCore core; + internal bool isWaiting; + + public SingleConsumerUnboundedChannelReader(SingleConsumerUnboundedChannel parent) + { + this.parent = parent; + + TaskTracker.TrackActiveTask(this, 4); + } + + public override UniTask Completion + { + get + { + if (parent.completedTaskSource != null) return parent.completedTaskSource.Task; + + if (parent.closed) + { + return parent.completedTask; + } + + parent.completedTaskSource = new UniTaskCompletionSource(); + return parent.completedTaskSource.Task; + } + } + + public override bool TryRead(out T item) + { + lock (parent.items) + { + if (parent.items.Count != 0) + { + item = parent.items.Dequeue(); + + // complete when all value was consumed. + if (parent.closed && parent.items.Count == 0) + { + if (parent.completionError != null) + { + if (parent.completedTaskSource != null) + { + parent.completedTaskSource.TrySetException(parent.completionError); + } + else + { + parent.completedTask = UniTask.FromException(parent.completionError); + } + } + else + { + if (parent.completedTaskSource != null) + { + parent.completedTaskSource.TrySetResult(); + } + else + { + parent.completedTask = UniTask.CompletedTask; + } + } + } + } + else + { + item = default; + return false; + } + } + + return true; + } + + public override UniTask WaitToReadAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return UniTask.FromCanceled(cancellationToken); + } + + lock (parent.items) + { + if (parent.items.Count != 0) + { + return CompletedTasks.True; + } + + if (parent.closed) + { + if (parent.completionError == null) + { + return CompletedTasks.False; + } + else + { + return UniTask.FromException(parent.completionError); + } + } + + cancellationTokenRegistration.Dispose(); + + core.Reset(); + isWaiting = true; + + this.cancellationToken = cancellationToken; + if (this.cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = this.cancellationToken.RegisterWithoutCaptureExecutionContext(CancellationCallbackDelegate, this); + } + + return new UniTask(this, core.Version); + } + } + + public void SingalContinuation() + { + core.TrySetResult(true); + } + + public void SingalCancellation(CancellationToken cancellationToken) + { + TaskTracker.RemoveTracking(this); + core.TrySetCanceled(cancellationToken); + } + + public void SingalCompleted(Exception error) + { + if (error != null) + { + TaskTracker.RemoveTracking(this); + core.TrySetException(error); + } + else + { + TaskTracker.RemoveTracking(this); + core.TrySetResult(false); + } + } + + public override IUniTaskAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken = default) + { + return new ReadAllAsyncEnumerable(this, cancellationToken); + } + + bool IUniTaskSource.GetResult(short token) + { + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + core.GetResult(token); + } + + UniTaskStatus IUniTaskSource.GetStatus(short token) + { + return core.GetStatus(token); + } + + void IUniTaskSource.OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + UniTaskStatus IUniTaskSource.UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + static void CancellationCallback(object state) + { + var self = (SingleConsumerUnboundedChannelReader)state; + self.SingalCancellation(self.cancellationToken); + } + + sealed class ReadAllAsyncEnumerable : IUniTaskAsyncEnumerable, IUniTaskAsyncEnumerator + { + readonly Action CancellationCallback1Delegate = CancellationCallback1; + readonly Action CancellationCallback2Delegate = CancellationCallback2; + + readonly SingleConsumerUnboundedChannelReader parent; + CancellationToken cancellationToken1; + CancellationToken cancellationToken2; + CancellationTokenRegistration cancellationTokenRegistration1; + CancellationTokenRegistration cancellationTokenRegistration2; + + T current; + bool cacheValue; + bool running; + + public ReadAllAsyncEnumerable(SingleConsumerUnboundedChannelReader parent, CancellationToken cancellationToken) + { + this.parent = parent; + this.cancellationToken1 = cancellationToken; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + if (running) + { + throw new InvalidOperationException("Enumerator is already running, does not allow call GetAsyncEnumerator twice."); + } + + if (this.cancellationToken1 != cancellationToken) + { + this.cancellationToken2 = cancellationToken; + } + + if (this.cancellationToken1.CanBeCanceled) + { + this.cancellationTokenRegistration1 = this.cancellationToken1.RegisterWithoutCaptureExecutionContext(CancellationCallback1Delegate, this); + } + + if (this.cancellationToken2.CanBeCanceled) + { + this.cancellationTokenRegistration2 = this.cancellationToken2.RegisterWithoutCaptureExecutionContext(CancellationCallback2Delegate, this); + } + + running = true; + return this; + } + + public T Current + { + get + { + if (cacheValue) + { + return current; + } + parent.TryRead(out current); + return current; + } + } + + public UniTask MoveNextAsync() + { + cacheValue = false; + return parent.WaitToReadAsync(CancellationToken.None); // ok to use None, registered in ctor. + } + + public UniTask DisposeAsync() + { + cancellationTokenRegistration1.Dispose(); + cancellationTokenRegistration2.Dispose(); + return default; + } + + static void CancellationCallback1(object state) + { + var self = (ReadAllAsyncEnumerable)state; + self.parent.SingalCancellation(self.cancellationToken1); + } + + static void CancellationCallback2(object state) + { + var self = (ReadAllAsyncEnumerable)state; + self.parent.SingalCancellation(self.cancellationToken2); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Channel.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Channel.cs.meta new file mode 100644 index 00000000..32edb9c0 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Channel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5ceb3107bbdd1f14eb39091273798360 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices.meta new file mode 100644 index 00000000..a4e896df --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 94d4f39a13c4c4343b06dae77c9004cb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs new file mode 100644 index 00000000..700fc339 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs @@ -0,0 +1,17 @@ + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS0436 + +namespace System.Runtime.CompilerServices +{ + internal sealed class AsyncMethodBuilderAttribute : Attribute + { + public Type BuilderType { get; } + + public AsyncMethodBuilderAttribute(Type builderType) + { + BuilderType = builderType; + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs.meta new file mode 100644 index 00000000..19961dfb --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 02ce354d37b10454e8376062f7cbe57a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs new file mode 100644 index 00000000..1aa990d9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs @@ -0,0 +1,269 @@ + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; + +namespace Cysharp.Threading.Tasks.CompilerServices +{ + [StructLayout(LayoutKind.Auto)] + public struct AsyncUniTaskMethodBuilder + { + IStateMachineRunnerPromise runnerPromise; + Exception ex; + + // 1. Static Create method. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncUniTaskMethodBuilder Create() + { + return default; + } + + // 2. TaskLike Task property. + public UniTask Task + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (runnerPromise != null) + { + return runnerPromise.Task; + } + else if (ex != null) + { + return UniTask.FromException(ex); + } + else + { + return UniTask.CompletedTask; + } + } + } + + // 3. SetException + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + if (runnerPromise == null) + { + ex = exception; + } + else + { + runnerPromise.SetException(exception); + } + } + + // 4. SetResult + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult() + { + if (runnerPromise != null) + { + runnerPromise.SetResult(); + } + } + + // 5. AwaitOnCompleted + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : INotifyCompletion + where TStateMachine : IAsyncStateMachine + { + if (runnerPromise == null) + { + AsyncUniTask.SetStateMachine(ref stateMachine, ref runnerPromise); + } + + awaiter.OnCompleted(runnerPromise.MoveNext); + } + + // 6. AwaitUnsafeOnCompleted + [DebuggerHidden] + [SecuritySafeCritical] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : ICriticalNotifyCompletion + where TStateMachine : IAsyncStateMachine + { + if (runnerPromise == null) + { + AsyncUniTask.SetStateMachine(ref stateMachine, ref runnerPromise); + } + + awaiter.UnsafeOnCompleted(runnerPromise.MoveNext); + } + + // 7. Start + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) + where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + + // 8. SetStateMachine + [DebuggerHidden] + public void SetStateMachine(IAsyncStateMachine stateMachine) + { + // don't use boxed stateMachine. + } + +#if DEBUG || !UNITY_2018_3_OR_NEWER + // Important for IDE debugger. + object debuggingId; + private object ObjectIdForDebugger + { + get + { + if (debuggingId == null) + { + debuggingId = new object(); + } + return debuggingId; + } + } +#endif + } + + [StructLayout(LayoutKind.Auto)] + public struct AsyncUniTaskMethodBuilder + { + IStateMachineRunnerPromise runnerPromise; + Exception ex; + T result; + + // 1. Static Create method. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncUniTaskMethodBuilder Create() + { + return default; + } + + // 2. TaskLike Task property. + public UniTask Task + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (runnerPromise != null) + { + return runnerPromise.Task; + } + else if (ex != null) + { + return UniTask.FromException(ex); + } + else + { + return UniTask.FromResult(result); + } + } + } + + // 3. SetException + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + if (runnerPromise == null) + { + ex = exception; + } + else + { + runnerPromise.SetException(exception); + } + } + + // 4. SetResult + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult(T result) + { + if (runnerPromise == null) + { + this.result = result; + } + else + { + runnerPromise.SetResult(result); + } + } + + // 5. AwaitOnCompleted + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : INotifyCompletion + where TStateMachine : IAsyncStateMachine + { + if (runnerPromise == null) + { + AsyncUniTask.SetStateMachine(ref stateMachine, ref runnerPromise); + } + + awaiter.OnCompleted(runnerPromise.MoveNext); + } + + // 6. AwaitUnsafeOnCompleted + [DebuggerHidden] + [SecuritySafeCritical] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : ICriticalNotifyCompletion + where TStateMachine : IAsyncStateMachine + { + if (runnerPromise == null) + { + AsyncUniTask.SetStateMachine(ref stateMachine, ref runnerPromise); + } + + awaiter.UnsafeOnCompleted(runnerPromise.MoveNext); + } + + // 7. Start + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Start(ref TStateMachine stateMachine) + where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + + // 8. SetStateMachine + [DebuggerHidden] + public void SetStateMachine(IAsyncStateMachine stateMachine) + { + // don't use boxed stateMachine. + } + +#if DEBUG || !UNITY_2018_3_OR_NEWER + // Important for IDE debugger. + object debuggingId; + private object ObjectIdForDebugger + { + get + { + if (debuggingId == null) + { + debuggingId = new object(); + } + return debuggingId; + } + } +#endif + + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs.meta new file mode 100644 index 00000000..ad43cfcf --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 68d72a45afdec574ebc26e7de2c38330 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskVoidMethodBuilder.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskVoidMethodBuilder.cs new file mode 100644 index 00000000..82e91f38 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskVoidMethodBuilder.cs @@ -0,0 +1,137 @@ + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; + +namespace Cysharp.Threading.Tasks.CompilerServices +{ + [StructLayout(LayoutKind.Auto)] + public struct AsyncUniTaskVoidMethodBuilder + { + IStateMachineRunner runner; + + // 1. Static Create method. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AsyncUniTaskVoidMethodBuilder Create() + { + return default; + } + + // 2. TaskLike Task property(void) + public UniTaskVoid Task + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return default; + } + } + + // 3. SetException + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetException(Exception exception) + { + // runner is finished, return first. + if (runner != null) + { +#if ENABLE_IL2CPP + // workaround for IL2CPP bug. + PlayerLoopHelper.AddContinuation(PlayerLoopTiming.LastPostLateUpdate, runner.ReturnAction); +#else + runner.Return(); +#endif + runner = null; + } + + UniTaskScheduler.PublishUnobservedTaskException(exception); + } + + // 4. SetResult + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetResult() + { + // runner is finished, return. + if (runner != null) + { +#if ENABLE_IL2CPP + // workaround for IL2CPP bug. + PlayerLoopHelper.AddContinuation(PlayerLoopTiming.LastPostLateUpdate, runner.ReturnAction); +#else + runner.Return(); +#endif + runner = null; + } + } + + // 5. AwaitOnCompleted + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : INotifyCompletion + where TStateMachine : IAsyncStateMachine + { + if (runner == null) + { + AsyncUniTaskVoid.SetStateMachine(ref stateMachine, ref runner); + } + + awaiter.OnCompleted(runner.MoveNext); + } + + // 6. AwaitUnsafeOnCompleted + [DebuggerHidden] + [SecuritySafeCritical] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : ICriticalNotifyCompletion + where TStateMachine : IAsyncStateMachine + { + if (runner == null) + { + AsyncUniTaskVoid.SetStateMachine(ref stateMachine, ref runner); + } + + awaiter.UnsafeOnCompleted(runner.MoveNext); + } + + // 7. Start + [DebuggerHidden] + public void Start(ref TStateMachine stateMachine) + where TStateMachine : IAsyncStateMachine + { + stateMachine.MoveNext(); + } + + // 8. SetStateMachine + [DebuggerHidden] + public void SetStateMachine(IAsyncStateMachine stateMachine) + { + // don't use boxed stateMachine. + } + +#if DEBUG || !UNITY_2018_3_OR_NEWER + // Important for IDE debugger. + object debuggingId; + private object ObjectIdForDebugger + { + get + { + if (debuggingId == null) + { + debuggingId = new object(); + } + return debuggingId; + } + } +#endif + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskVoidMethodBuilder.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskVoidMethodBuilder.cs.meta new file mode 100644 index 00000000..9bcc50e0 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/AsyncUniTaskVoidMethodBuilder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e891aaac17b933a47a9d7fa3b8e1226f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs new file mode 100644 index 00000000..1cffeced --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs @@ -0,0 +1,380 @@ +#pragma warning disable CS1591 + +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Linq; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.CompilerServices +{ + // #ENABLE_IL2CPP in this file is to avoid bug of IL2CPP VM. + // Issue is tracked on https://issuetracker.unity3d.com/issues/il2cpp-incorrect-results-when-calling-a-method-from-outside-class-in-a-struct + // but currently it is labeled `Won't Fix`. + + internal interface IStateMachineRunner + { + Action MoveNext { get; } + void Return(); + +#if ENABLE_IL2CPP + Action ReturnAction { get; } +#endif + } + + internal interface IStateMachineRunnerPromise : IUniTaskSource + { + Action MoveNext { get; } + UniTask Task { get; } + void SetResult(); + void SetException(Exception exception); + } + + internal interface IStateMachineRunnerPromise : IUniTaskSource + { + Action MoveNext { get; } + UniTask Task { get; } + void SetResult(T result); + void SetException(Exception exception); + } + + internal static class StateMachineUtility + { + // Get AsyncStateMachine internal state to check IL2CPP bug + public static int GetState(IAsyncStateMachine stateMachine) + { + var info = stateMachine.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) + .First(x => x.Name.EndsWith("__state")); + return (int)info.GetValue(stateMachine); + } + } + + internal sealed class AsyncUniTaskVoid : IStateMachineRunner, ITaskPoolNode>, IUniTaskSource + where TStateMachine : IAsyncStateMachine + { + static TaskPool> pool; + +#if ENABLE_IL2CPP + public Action ReturnAction { get; } +#endif + + TStateMachine stateMachine; + + public Action MoveNext { get; } + + public AsyncUniTaskVoid() + { + MoveNext = Run; +#if ENABLE_IL2CPP + ReturnAction = Return; +#endif + } + + public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunner runnerFieldRef) + { + if (!pool.TryPop(out var result)) + { + result = new AsyncUniTaskVoid(); + } + TaskTracker.TrackActiveTask(result, 3); + + runnerFieldRef = result; // set runner before copied. + result.stateMachine = stateMachine; // copy struct StateMachine(in release build). + } + + static AsyncUniTaskVoid() + { + TaskPool.RegisterSizeGetter(typeof(AsyncUniTaskVoid), () => pool.Size); + } + + AsyncUniTaskVoid nextNode; + public ref AsyncUniTaskVoid NextNode => ref nextNode; + + public void Return() + { + TaskTracker.RemoveTracking(this); + stateMachine = default; + pool.TryPush(this); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void Run() + { + stateMachine.MoveNext(); + } + + // dummy interface implementation for TaskTracker. + + UniTaskStatus IUniTaskSource.GetStatus(short token) + { + return UniTaskStatus.Pending; + } + + UniTaskStatus IUniTaskSource.UnsafeGetStatus() + { + return UniTaskStatus.Pending; + } + + void IUniTaskSource.OnCompleted(Action continuation, object state, short token) + { + } + + void IUniTaskSource.GetResult(short token) + { + } + } + + internal sealed class AsyncUniTask : IStateMachineRunnerPromise, IUniTaskSource, ITaskPoolNode> + where TStateMachine : IAsyncStateMachine + { + static TaskPool> pool; + +#if ENABLE_IL2CPP + readonly Action returnDelegate; +#endif + public Action MoveNext { get; } + + TStateMachine stateMachine; + UniTaskCompletionSourceCore core; + + AsyncUniTask() + { + MoveNext = Run; +#if ENABLE_IL2CPP + returnDelegate = Return; +#endif + } + + public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise runnerPromiseFieldRef) + { + if (!pool.TryPop(out var result)) + { + result = new AsyncUniTask(); + } + TaskTracker.TrackActiveTask(result, 3); + + runnerPromiseFieldRef = result; // set runner before copied. + result.stateMachine = stateMachine; // copy struct StateMachine(in release build). + } + + AsyncUniTask nextNode; + public ref AsyncUniTask NextNode => ref nextNode; + + static AsyncUniTask() + { + TaskPool.RegisterSizeGetter(typeof(AsyncUniTask), () => pool.Size); + } + + void Return() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + stateMachine = default; + pool.TryPush(this); + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + stateMachine = default; + return pool.TryPush(this); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void Run() + { + stateMachine.MoveNext(); + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, core.Version); + } + } + + [DebuggerHidden] + public void SetResult() + { + core.TrySetResult(AsyncUnit.Default); + } + + [DebuggerHidden] + public void SetException(Exception exception) + { + core.TrySetException(exception); + } + + [DebuggerHidden] + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { +#if ENABLE_IL2CPP + // workaround for IL2CPP bug. + PlayerLoopHelper.AddContinuation(PlayerLoopTiming.LastPostLateUpdate, returnDelegate); +#else + TryReturn(); +#endif + } + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + internal sealed class AsyncUniTask : IStateMachineRunnerPromise, IUniTaskSource, ITaskPoolNode> + where TStateMachine : IAsyncStateMachine + { + static TaskPool> pool; + +#if ENABLE_IL2CPP + readonly Action returnDelegate; +#endif + + public Action MoveNext { get; } + + TStateMachine stateMachine; + UniTaskCompletionSourceCore core; + + AsyncUniTask() + { + MoveNext = Run; +#if ENABLE_IL2CPP + returnDelegate = Return; +#endif + } + + public static void SetStateMachine(ref TStateMachine stateMachine, ref IStateMachineRunnerPromise runnerPromiseFieldRef) + { + if (!pool.TryPop(out var result)) + { + result = new AsyncUniTask(); + } + TaskTracker.TrackActiveTask(result, 3); + + runnerPromiseFieldRef = result; // set runner before copied. + result.stateMachine = stateMachine; // copy struct StateMachine(in release build). + } + + AsyncUniTask nextNode; + public ref AsyncUniTask NextNode => ref nextNode; + + static AsyncUniTask() + { + TaskPool.RegisterSizeGetter(typeof(AsyncUniTask), () => pool.Size); + } + + void Return() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + stateMachine = default; + pool.TryPush(this); + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + stateMachine = default; + return pool.TryPush(this); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void Run() + { + // UnityEngine.Debug.Log($"MoveNext State:" + StateMachineUtility.GetState(stateMachine)); + stateMachine.MoveNext(); + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, core.Version); + } + } + + [DebuggerHidden] + public void SetResult(T result) + { + core.TrySetResult(result); + } + + [DebuggerHidden] + public void SetException(Exception exception) + { + core.TrySetException(exception); + } + + [DebuggerHidden] + public T GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { +#if ENABLE_IL2CPP + // workaround for IL2CPP bug. + PlayerLoopHelper.AddContinuation(PlayerLoopTiming.LastPostLateUpdate, returnDelegate); +#else + TryReturn(); +#endif + } + } + + [DebuggerHidden] + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs.meta new file mode 100644 index 00000000..2cb82e08 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/CompilerServices/StateMachineRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 98649642833cabf44a9dc060ce4c84a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs new file mode 100644 index 00000000..004e7631 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs @@ -0,0 +1,34 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; + +namespace Cysharp.Threading.Tasks +{ + public static class EnumerableAsyncExtensions + { + // overload resolver - .Select(async x => { }) : IEnumerable> + + public static IEnumerable Select(this IEnumerable source, Func selector) + { + return System.Linq.Enumerable.Select(source, selector); + } + + public static IEnumerable> Select(this IEnumerable source, Func> selector) + { + return System.Linq.Enumerable.Select(source, selector); + } + + public static IEnumerable Select(this IEnumerable source, Func selector) + { + return System.Linq.Enumerable.Select(source, selector); + } + + public static IEnumerable> Select(this IEnumerable source, Func> selector) + { + return System.Linq.Enumerable.Select(source, selector); + } + } +} + + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs.meta new file mode 100644 index 00000000..d2e49304 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ff50260d74bd54c4b92cf99895549445 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/EnumeratorAsyncExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumeratorAsyncExtensions.cs new file mode 100644 index 00000000..785bbc28 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumeratorAsyncExtensions.cs @@ -0,0 +1,287 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; +using UnityEngine; + +namespace Cysharp.Threading.Tasks +{ + public static class EnumeratorAsyncExtensions + { + public static UniTask.Awaiter GetAwaiter(this T enumerator) + where T : IEnumerator + { + var e = (IEnumerator)enumerator; + Error.ThrowArgumentNullException(e, nameof(enumerator)); + return new UniTask(EnumeratorPromise.Create(e, PlayerLoopTiming.Update, CancellationToken.None, out var token), token).GetAwaiter(); + } + + public static UniTask WithCancellation(this IEnumerator enumerator, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(enumerator, nameof(enumerator)); + return new UniTask(EnumeratorPromise.Create(enumerator, PlayerLoopTiming.Update, cancellationToken, out var token), token); + } + + public static UniTask ToUniTask(this IEnumerator enumerator, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken)) + { + Error.ThrowArgumentNullException(enumerator, nameof(enumerator)); + return new UniTask(EnumeratorPromise.Create(enumerator, timing, cancellationToken, out var token), token); + } + + public static UniTask ToUniTask(this IEnumerator enumerator, MonoBehaviour coroutineRunner) + { + var source = AutoResetUniTaskCompletionSource.Create(); + coroutineRunner.StartCoroutine(Core(enumerator, coroutineRunner, source)); + return source.Task; + } + + static IEnumerator Core(IEnumerator inner, MonoBehaviour coroutineRunner, AutoResetUniTaskCompletionSource source) + { + yield return coroutineRunner.StartCoroutine(inner); + source.TrySetResult(); + } + + sealed class EnumeratorPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + EnumeratorPromise nextNode; + public ref EnumeratorPromise NextNode => ref nextNode; + + static EnumeratorPromise() + { + TaskPool.RegisterSizeGetter(typeof(EnumeratorPromise), () => pool.Size); + } + + IEnumerator innerEnumerator; + CancellationToken cancellationToken; + int initialFrame; + bool loopRunning; + bool calledGetResult; + + UniTaskCompletionSourceCore core; + + EnumeratorPromise() + { + } + + public static IUniTaskSource Create(IEnumerator innerEnumerator, PlayerLoopTiming timing, CancellationToken cancellationToken, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new EnumeratorPromise(); + } + TaskTracker.TrackActiveTask(result, 3); + + result.innerEnumerator = ConsumeEnumerator(innerEnumerator); + result.cancellationToken = cancellationToken; + result.loopRunning = true; + result.calledGetResult = false; + result.initialFrame = -1; + + token = result.core.Version; + + // run immediately. + if (result.MoveNext()) + { + PlayerLoopHelper.AddAction(timing, result); + } + + return result; + } + + public void GetResult(short token) + { + try + { + calledGetResult = true; + core.GetResult(token); + } + finally + { + if (!loopRunning) + { + TryReturn(); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (calledGetResult) + { + loopRunning = false; + TryReturn(); + return false; + } + + if (innerEnumerator == null) // invalid status, returned but loop running? + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + loopRunning = false; + core.TrySetCanceled(cancellationToken); + return false; + } + + if (initialFrame == -1) + { + // Time can not touch in threadpool. + if (PlayerLoopHelper.IsMainThread) + { + initialFrame = Time.frameCount; + } + } + else if (initialFrame == Time.frameCount) + { + return true; // already executed in first frame, skip. + } + + try + { + if (innerEnumerator.MoveNext()) + { + return true; + } + } + catch (Exception ex) + { + loopRunning = false; + core.TrySetException(ex); + return false; + } + + loopRunning = false; + core.TrySetResult(null); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + innerEnumerator = default; + cancellationToken = default; + + return pool.TryPush(this); + } + + // Unwrap YieldInstructions + + static IEnumerator ConsumeEnumerator(IEnumerator enumerator) + { + while (enumerator.MoveNext()) + { + var current = enumerator.Current; + if (current == null) + { + yield return null; + } + else if (current is CustomYieldInstruction cyi) + { + // WWW, WaitForSecondsRealtime + while (cyi.keepWaiting) + { + yield return null; + } + } + else if (current is YieldInstruction) + { + IEnumerator innerCoroutine = null; + switch (current) + { + case AsyncOperation ao: + innerCoroutine = UnwrapWaitAsyncOperation(ao); + break; + case WaitForSeconds wfs: + innerCoroutine = UnwrapWaitForSeconds(wfs); + break; + } + if (innerCoroutine != null) + { + while (innerCoroutine.MoveNext()) + { + yield return null; + } + } + else + { + goto WARN; + } + } + else if (current is IEnumerator e3) + { + var e4 = ConsumeEnumerator(e3); + while (e4.MoveNext()) + { + yield return null; + } + } + else + { + goto WARN; + } + + continue; + + WARN: + // WaitForEndOfFrame, WaitForFixedUpdate, others. + UnityEngine.Debug.LogWarning($"yield {current.GetType().Name} is not supported on await IEnumerator or IEnumerator.ToUniTask(), please use ToUniTask(MonoBehaviour coroutineRunner) instead."); + yield return null; + } + } + + static readonly FieldInfo waitForSeconds_Seconds = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic); + + static IEnumerator UnwrapWaitForSeconds(WaitForSeconds waitForSeconds) + { + var second = (float)waitForSeconds_Seconds.GetValue(waitForSeconds); + var elapsed = 0.0f; + while (true) + { + yield return null; + + elapsed += Time.deltaTime; + if (elapsed >= second) + { + break; + } + }; + } + + static IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation) + { + while (!asyncOperation.isDone) + { + yield return null; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/EnumeratorAsyncExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumeratorAsyncExtensions.cs.meta new file mode 100644 index 00000000..a07b336d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/EnumeratorAsyncExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc661232f11e4a741af54ba1c175d5ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/ExceptionExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/ExceptionExtensions.cs new file mode 100644 index 00000000..e4118980 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/ExceptionExtensions.cs @@ -0,0 +1,14 @@ + +using System; + +namespace Cysharp.Threading.Tasks +{ + public static class ExceptionExtensions + { + public static bool IsOperationCanceledException(this Exception exception) + { + return exception is OperationCanceledException; + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/ExceptionExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/ExceptionExtensions.cs.meta new file mode 100644 index 00000000..98330016 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/ExceptionExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 930800098504c0d46958ce23a0495202 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External.meta new file mode 100644 index 00000000..878364c3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 098e5c37c2586684e8ccdfdf2841d928 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables.meta new file mode 100644 index 00000000..d0d520b5 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 68bbb00e91516484d90c919bd93d0e7e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs new file mode 100644 index 00000000..0c77c52c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs @@ -0,0 +1,483 @@ +// asmdef Version Defines, enabled when com.unity.addressables is imported. + +#if UNITASK_ADDRESSABLE_SUPPORT + +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Threading; +using UnityEngine.AddressableAssets; +using UnityEngine.ResourceManagement.AsyncOperations; + +namespace Cysharp.Threading.Tasks +{ + public static class AddressablesAsyncExtensions + { +#region AsyncOperationHandle + + public static UniTask.Awaiter GetAwaiter(this AsyncOperationHandle handle) + { + return ToUniTask(handle).GetAwaiter(); + } + + public static UniTask WithCancellation(this AsyncOperationHandle handle, CancellationToken cancellationToken, bool cancelImmediately = false, bool autoReleaseWhenCanceled = false) + { + return ToUniTask(handle, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately, autoReleaseWhenCanceled: autoReleaseWhenCanceled); + } + + public static UniTask ToUniTask(this AsyncOperationHandle handle, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false, bool autoReleaseWhenCanceled = false) + { + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + + if (!handle.IsValid()) + { + // autoReleaseHandle:true handle is invalid(immediately internal handle == null) so return completed. + return UniTask.CompletedTask; + } + + if (handle.IsDone) + { + if (handle.Status == AsyncOperationStatus.Failed) + { + return UniTask.FromException(handle.OperationException); + } + return UniTask.CompletedTask; + } + + return new UniTask(AsyncOperationHandleConfiguredSource.Create(handle, timing, progress, cancellationToken, cancelImmediately, autoReleaseWhenCanceled, out var token), token); + } + + public struct AsyncOperationHandleAwaiter : ICriticalNotifyCompletion + { + AsyncOperationHandle handle; + Action continuationAction; + + public AsyncOperationHandleAwaiter(AsyncOperationHandle handle) + { + this.handle = handle; + this.continuationAction = null; + } + + public bool IsCompleted => handle.IsDone; + + public void GetResult() + { + if (continuationAction != null) + { + handle.Completed -= continuationAction; + continuationAction = null; + } + + if (handle.Status == AsyncOperationStatus.Failed) + { + var e = handle.OperationException; + handle = default; + ExceptionDispatchInfo.Capture(e).Throw(); + } + + var result = handle.Result; + handle = default; + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + handle.Completed += continuationAction; + } + } + + sealed class AsyncOperationHandleConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AsyncOperationHandleConfiguredSource nextNode; + public ref AsyncOperationHandleConfiguredSource NextNode => ref nextNode; + + static AsyncOperationHandleConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AsyncOperationHandleConfiguredSource), () => pool.Size); + } + + readonly Action completedCallback; + AsyncOperationHandle handle; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + IProgress progress; + bool autoReleaseWhenCanceled; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + AsyncOperationHandleConfiguredSource() + { + completedCallback = HandleCompleted; + } + + public static IUniTaskSource Create(AsyncOperationHandle handle, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, bool autoReleaseWhenCanceled, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AsyncOperationHandleConfiguredSource(); + } + + result.handle = handle; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.autoReleaseWhenCanceled = autoReleaseWhenCanceled; + result.completed = false; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (AsyncOperationHandleConfiguredSource)state; + if (promise.autoReleaseWhenCanceled && promise.handle.IsValid()) + { + Addressables.Release(promise.handle); + } + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + handle.Completed += result.completedCallback; + + token = result.core.Version; + return result; + } + + void HandleCompleted(AsyncOperationHandle _) + { + if (handle.IsValid()) + { + handle.Completed -= completedCallback; + } + + if (completed) + { + return; + } + + completed = true; + if (cancellationToken.IsCancellationRequested) + { + if (autoReleaseWhenCanceled && handle.IsValid()) + { + Addressables.Release(handle); + } + core.TrySetCanceled(cancellationToken); + } + else if (handle.Status == AsyncOperationStatus.Failed) + { + core.TrySetException(handle.OperationException); + } + else + { + core.TrySetResult(AsyncUnit.Default); + } + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (completed) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + completed = true; + if (autoReleaseWhenCanceled && handle.IsValid()) + { + Addressables.Release(handle); + } + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null && handle.IsValid()) + { + progress.Report(handle.GetDownloadStatus().Percent); + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + handle = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + return pool.TryPush(this); + } + } + +#endregion + +#region AsyncOperationHandle_T + + public static UniTask.Awaiter GetAwaiter(this AsyncOperationHandle handle) + { + return ToUniTask(handle).GetAwaiter(); + } + + public static UniTask WithCancellation(this AsyncOperationHandle handle, CancellationToken cancellationToken, bool cancelImmediately = false, bool autoReleaseWhenCanceled = false) + { + return ToUniTask(handle, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately, autoReleaseWhenCanceled: autoReleaseWhenCanceled); + } + + public static UniTask ToUniTask(this AsyncOperationHandle handle, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false, bool autoReleaseWhenCanceled = false) + { + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + + if (!handle.IsValid()) + { + throw new Exception("Attempting to use an invalid operation handle"); + } + + if (handle.IsDone) + { + if (handle.Status == AsyncOperationStatus.Failed) + { + return UniTask.FromException(handle.OperationException); + } + return UniTask.FromResult(handle.Result); + } + + return new UniTask(AsyncOperationHandleConfiguredSource.Create(handle, timing, progress, cancellationToken, cancelImmediately, autoReleaseWhenCanceled, out var token), token); + } + + sealed class AsyncOperationHandleConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> + { + static TaskPool> pool; + AsyncOperationHandleConfiguredSource nextNode; + public ref AsyncOperationHandleConfiguredSource NextNode => ref nextNode; + + static AsyncOperationHandleConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AsyncOperationHandleConfiguredSource), () => pool.Size); + } + + readonly Action> completedCallback; + AsyncOperationHandle handle; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + IProgress progress; + bool autoReleaseWhenCanceled; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + AsyncOperationHandleConfiguredSource() + { + completedCallback = HandleCompleted; + } + + public static IUniTaskSource Create(AsyncOperationHandle handle, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, bool autoReleaseWhenCanceled, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AsyncOperationHandleConfiguredSource(); + } + + result.handle = handle; + result.cancellationToken = cancellationToken; + result.completed = false; + result.progress = progress; + result.autoReleaseWhenCanceled = autoReleaseWhenCanceled; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (AsyncOperationHandleConfiguredSource)state; + if (promise.autoReleaseWhenCanceled && promise.handle.IsValid()) + { + Addressables.Release(promise.handle); + } + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + handle.Completed += result.completedCallback; + + token = result.core.Version; + return result; + } + + void HandleCompleted(AsyncOperationHandle argHandle) + { + if (handle.IsValid()) + { + handle.Completed -= completedCallback; + } + + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + if (autoReleaseWhenCanceled && handle.IsValid()) + { + Addressables.Release(handle); + } + core.TrySetCanceled(cancellationToken); + } + else if (argHandle.Status == AsyncOperationStatus.Failed) + { + core.TrySetException(argHandle.OperationException); + } + else + { + core.TrySetResult(argHandle.Result); + } + } + + public T GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (completed) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + completed = true; + if (autoReleaseWhenCanceled && handle.IsValid()) + { + Addressables.Release(handle); + } + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null && handle.IsValid()) + { + progress.Report(handle.GetDownloadStatus().Percent); + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + handle = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + return pool.TryPush(this); + } + } + +#endregion + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs.meta new file mode 100644 index 00000000..6927930d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/AddressablesAsyncExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3dc6441f9094f354b931dc3c79fb99e5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/UniTask.Addressables.asmdef b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/UniTask.Addressables.asmdef new file mode 100644 index 00000000..faed8eca --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/UniTask.Addressables.asmdef @@ -0,0 +1,28 @@ +{ + "name": "UniTask.Addressables", + "references": [ + "UniTask", + "Unity.ResourceManager", + "Unity.Addressables" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.addressables", + "expression": "", + "define": "UNITASK_ADDRESSABLE_SUPPORT" + }, + { + "name": "com.unity.addressables.cn", + "expression": "", + "define": "UNITASK_ADDRESSABLE_SUPPORT" + } + ], + "noEngineReferences": false +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/UniTask.Addressables.asmdef.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/UniTask.Addressables.asmdef.meta new file mode 100644 index 00000000..b0178c4a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/Addressables/UniTask.Addressables.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 593a5b492d29ac6448b1ebf7f035ef33 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween.meta new file mode 100644 index 00000000..3a11d457 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 63d6cebb3cfc5024ba83a181e6f521a3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/DOTweenAsyncExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/DOTweenAsyncExtensions.cs new file mode 100644 index 00000000..ba783672 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/DOTweenAsyncExtensions.cs @@ -0,0 +1,436 @@ +// asmdef Version Defines, enabled when com.demigiant.dotween is imported. + +#if UNITASK_DOTWEEN_SUPPORT + +using Cysharp.Threading.Tasks.Internal; +using DG.Tweening; +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public enum TweenCancelBehaviour + { + Kill, + KillWithCompleteCallback, + Complete, + CompleteWithSequenceCallback, + CancelAwait, + + // AndCancelAwait + KillAndCancelAwait, + KillWithCompleteCallbackAndCancelAwait, + CompleteAndCancelAwait, + CompleteWithSequenceCallbackAndCancelAwait + } + + public static class DOTweenAsyncExtensions + { + enum CallbackType + { + Kill, + Complete, + Pause, + Play, + Rewind, + StepComplete + } + + public static TweenAwaiter GetAwaiter(this Tween tween) + { + return new TweenAwaiter(tween); + } + + public static UniTask WithCancellation(this Tween tween, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, TweenCancelBehaviour.Kill, cancellationToken, CallbackType.Kill, out var token), token); + } + + public static UniTask ToUniTask(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Kill, out var token), token); + } + + public static UniTask AwaitForComplete(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Complete, out var token), token); + } + + public static UniTask AwaitForPause(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Pause, out var token), token); + } + + public static UniTask AwaitForPlay(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Play, out var token), token); + } + + public static UniTask AwaitForRewind(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.Rewind, out var token), token); + } + + public static UniTask AwaitForStepComplete(this Tween tween, TweenCancelBehaviour tweenCancelBehaviour = TweenCancelBehaviour.Kill, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(tween, nameof(tween)); + + if (!tween.IsActive()) return UniTask.CompletedTask; + return new UniTask(TweenConfiguredSource.Create(tween, tweenCancelBehaviour, cancellationToken, CallbackType.StepComplete, out var token), token); + } + + public struct TweenAwaiter : ICriticalNotifyCompletion + { + readonly Tween tween; + + // killed(non active) as completed. + public bool IsCompleted => !tween.IsActive(); + + public TweenAwaiter(Tween tween) + { + this.tween = tween; + } + + public TweenAwaiter GetAwaiter() + { + return this; + } + + public void GetResult() + { + } + + public void OnCompleted(System.Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(System.Action continuation) + { + // onKill is called after OnCompleted, both Complete(false/true) and Kill(false/true). + tween.onKill = PooledTweenCallback.Create(continuation); + } + } + + sealed class TweenConfiguredSource : IUniTaskSource, ITaskPoolNode + { + static TaskPool pool; + TweenConfiguredSource nextNode; + public ref TweenConfiguredSource NextNode => ref nextNode; + + static TweenConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(TweenConfiguredSource), () => pool.Size); + } + + readonly TweenCallback onCompleteCallbackDelegate; + + Tween tween; + TweenCancelBehaviour cancelBehaviour; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationRegistration; + CallbackType callbackType; + bool canceled; + + TweenCallback originalCompleteAction; + UniTaskCompletionSourceCore core; + + TweenConfiguredSource() + { + onCompleteCallbackDelegate = OnCompleteCallbackDelegate; + } + + public static IUniTaskSource Create(Tween tween, TweenCancelBehaviour cancelBehaviour, CancellationToken cancellationToken, CallbackType callbackType, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + DoCancelBeforeCreate(tween, cancelBehaviour); + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new TweenConfiguredSource(); + } + + result.tween = tween; + result.cancelBehaviour = cancelBehaviour; + result.cancellationToken = cancellationToken; + result.callbackType = callbackType; + result.canceled = false; + + switch (callbackType) + { + case CallbackType.Kill: + result.originalCompleteAction = tween.onKill; + tween.onKill = result.onCompleteCallbackDelegate; + break; + case CallbackType.Complete: + result.originalCompleteAction = tween.onComplete; + tween.onComplete = result.onCompleteCallbackDelegate; + break; + case CallbackType.Pause: + result.originalCompleteAction = tween.onPause; + tween.onPause = result.onCompleteCallbackDelegate; + break; + case CallbackType.Play: + result.originalCompleteAction = tween.onPlay; + tween.onPlay = result.onCompleteCallbackDelegate; + break; + case CallbackType.Rewind: + result.originalCompleteAction = tween.onRewind; + tween.onRewind = result.onCompleteCallbackDelegate; + break; + case CallbackType.StepComplete: + result.originalCompleteAction = tween.onStepComplete; + tween.onStepComplete = result.onCompleteCallbackDelegate; + break; + default: + break; + } + + if (result.originalCompleteAction == result.onCompleteCallbackDelegate) + { + result.originalCompleteAction = null; + } + + if (cancellationToken.CanBeCanceled) + { + result.cancellationRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(x => + { + var source = (TweenConfiguredSource)x; + switch (source.cancelBehaviour) + { + case TweenCancelBehaviour.Kill: + default: + source.tween.Kill(false); + break; + case TweenCancelBehaviour.KillAndCancelAwait: + source.canceled = true; + source.tween.Kill(false); + break; + case TweenCancelBehaviour.KillWithCompleteCallback: + source.tween.Kill(true); + break; + case TweenCancelBehaviour.KillWithCompleteCallbackAndCancelAwait: + source.canceled = true; + source.tween.Kill(true); + break; + case TweenCancelBehaviour.Complete: + source.tween.Complete(false); + break; + case TweenCancelBehaviour.CompleteAndCancelAwait: + source.canceled = true; + source.tween.Complete(false); + break; + case TweenCancelBehaviour.CompleteWithSequenceCallback: + source.tween.Complete(true); + break; + case TweenCancelBehaviour.CompleteWithSequenceCallbackAndCancelAwait: + source.canceled = true; + source.tween.Complete(true); + break; + case TweenCancelBehaviour.CancelAwait: + source.RestoreOriginalCallback(); + source.core.TrySetCanceled(source.cancellationToken); + break; + } + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + token = result.core.Version; + return result; + } + + void OnCompleteCallbackDelegate() + { + if (cancellationToken.IsCancellationRequested) + { + if (this.cancelBehaviour == TweenCancelBehaviour.KillAndCancelAwait + || this.cancelBehaviour == TweenCancelBehaviour.KillWithCompleteCallbackAndCancelAwait + || this.cancelBehaviour == TweenCancelBehaviour.CompleteAndCancelAwait + || this.cancelBehaviour == TweenCancelBehaviour.CompleteWithSequenceCallbackAndCancelAwait + || this.cancelBehaviour == TweenCancelBehaviour.CancelAwait) + { + canceled = true; + } + } + if (canceled) + { + core.TrySetCanceled(cancellationToken); + } + else + { + originalCompleteAction?.Invoke(); + core.TrySetResult(AsyncUnit.Default); + } + } + + static void DoCancelBeforeCreate(Tween tween, TweenCancelBehaviour tweenCancelBehaviour) + { + + switch (tweenCancelBehaviour) + { + case TweenCancelBehaviour.Kill: + default: + tween.Kill(false); + break; + case TweenCancelBehaviour.KillAndCancelAwait: + tween.Kill(false); + break; + case TweenCancelBehaviour.KillWithCompleteCallback: + tween.Kill(true); + break; + case TweenCancelBehaviour.KillWithCompleteCallbackAndCancelAwait: + tween.Kill(true); + break; + case TweenCancelBehaviour.Complete: + tween.Complete(false); + break; + case TweenCancelBehaviour.CompleteAndCancelAwait: + tween.Complete(false); + break; + case TweenCancelBehaviour.CompleteWithSequenceCallback: + tween.Complete(true); + break; + case TweenCancelBehaviour.CompleteWithSequenceCallbackAndCancelAwait: + tween.Complete(true); + break; + case TweenCancelBehaviour.CancelAwait: + break; + } + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + cancellationRegistration.Dispose(); + + RestoreOriginalCallback(); + + tween = default; + cancellationToken = default; + originalCompleteAction = default; + return pool.TryPush(this); + } + + void RestoreOriginalCallback() + { + switch (callbackType) + { + case CallbackType.Kill: + tween.onKill = originalCompleteAction; + break; + case CallbackType.Complete: + tween.onComplete = originalCompleteAction; + break; + case CallbackType.Pause: + tween.onPause = originalCompleteAction; + break; + case CallbackType.Play: + tween.onPlay = originalCompleteAction; + break; + case CallbackType.Rewind: + tween.onRewind = originalCompleteAction; + break; + case CallbackType.StepComplete: + tween.onStepComplete = originalCompleteAction; + break; + default: + break; + } + } + } + } + + sealed class PooledTweenCallback + { + static readonly ConcurrentQueue pool = new ConcurrentQueue(); + + readonly TweenCallback runDelegate; + + Action continuation; + + + PooledTweenCallback() + { + runDelegate = Run; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TweenCallback Create(Action continuation) + { + if (!pool.TryDequeue(out var item)) + { + item = new PooledTweenCallback(); + } + + item.continuation = continuation; + return item.runDelegate; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void Run() + { + var call = continuation; + continuation = null; + if (call != null) + { + pool.Enqueue(this); + call.Invoke(); + } + } + } +} + +#endif diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/DOTweenAsyncExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/DOTweenAsyncExtensions.cs.meta new file mode 100644 index 00000000..63131b04 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/DOTweenAsyncExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f448d5bc5b232e4f98d89d5d1832e8e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/UniTask.DOTween.asmdef b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/UniTask.DOTween.asmdef new file mode 100644 index 00000000..7bdb2b61 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/UniTask.DOTween.asmdef @@ -0,0 +1,22 @@ +{ + "name": "UniTask.DOTween", + "references": [ + "UniTask", + "DOTween.Modules" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.demigiant.dotween", + "expression": "", + "define": "UNITASK_DOTWEEN_SUPPORT" + } + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/UniTask.DOTween.asmdef.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/UniTask.DOTween.asmdef.meta new file mode 100644 index 00000000..427fe290 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/DOTween/UniTask.DOTween.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 029c1c1b674aaae47a6841a0b89ad80e +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro.meta new file mode 100644 index 00000000..7c6931ab --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4ac6688580f587748af49735765ace92 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.InputField.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.InputField.cs new file mode 100644 index 00000000..22f081c2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.InputField.cs @@ -0,0 +1,224 @@ +#if UNITASK_TEXTMESHPRO_SUPPORT + +using System; +using System.Threading; +using TMPro; + +namespace Cysharp.Threading.Tasks +{ + public static partial class TextMeshProAsyncExtensions + { + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onValueChanged, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onValueChanged, cancellationToken); + } + + public static IAsyncEndEditEventHandler GetAsyncEndEditEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncEndEditEventHandler GetAsyncEndEditEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, cancellationToken, false); + } + + public static UniTask OnEndEditAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnEndEditAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnEndEditAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onEndEdit, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnEndEditAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onEndEdit, cancellationToken); + } + + public static IAsyncEndTextSelectionEventHandler<(string, int, int)> GetAsyncEndTextSelectionEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onEndTextSelection), inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncEndTextSelectionEventHandler<(string, int, int)> GetAsyncEndTextSelectionEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onEndTextSelection), cancellationToken, false); + } + + public static UniTask<(string, int, int)> OnEndTextSelectionAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onEndTextSelection), inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask<(string, int, int)> OnEndTextSelectionAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onEndTextSelection), cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable<(string, int, int)> OnEndTextSelectionAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable<(string, int, int)>(new TextSelectionEventConverter(inputField.onEndTextSelection), inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable<(string, int, int)> OnEndTextSelectionAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable<(string, int, int)>(new TextSelectionEventConverter(inputField.onEndTextSelection), cancellationToken); + } + + public static IAsyncTextSelectionEventHandler<(string, int, int)> GetAsyncTextSelectionEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onTextSelection), inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncTextSelectionEventHandler<(string, int, int)> GetAsyncTextSelectionEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onTextSelection), cancellationToken, false); + } + + public static UniTask<(string, int, int)> OnTextSelectionAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onTextSelection), inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask<(string, int, int)> OnTextSelectionAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler<(string, int, int)>(new TextSelectionEventConverter(inputField.onTextSelection), cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable<(string, int, int)> OnTextSelectionAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable<(string, int, int)>(new TextSelectionEventConverter(inputField.onTextSelection), inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable<(string, int, int)> OnTextSelectionAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable<(string, int, int)>(new TextSelectionEventConverter(inputField.onTextSelection), cancellationToken); + } + + public static IAsyncDeselectEventHandler GetAsyncDeselectEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onDeselect, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncDeselectEventHandler GetAsyncDeselectEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onDeselect, cancellationToken, false); + } + + public static UniTask OnDeselectAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onDeselect, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnDeselectAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onDeselect, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnDeselectAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onDeselect, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnDeselectAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onDeselect, cancellationToken); + } + + public static IAsyncSelectEventHandler GetAsyncSelectEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onSelect, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncSelectEventHandler GetAsyncSelectEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onSelect, cancellationToken, false); + } + + public static UniTask OnSelectAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onSelect, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnSelectAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onSelect, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnSelectAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onSelect, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnSelectAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onSelect, cancellationToken); + } + + public static IAsyncSubmitEventHandler GetAsyncSubmitEventHandler(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onSubmit, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncSubmitEventHandler GetAsyncSubmitEventHandler(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onSubmit, cancellationToken, false); + } + + public static UniTask OnSubmitAsync(this TMP_InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onSubmit, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnSubmitAsync(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onSubmit, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnSubmitAsAsyncEnumerable(this TMP_InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onSubmit, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnSubmitAsAsyncEnumerable(this TMP_InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onSubmit, cancellationToken); + } + + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.InputField.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.InputField.cs.meta new file mode 100644 index 00000000..2e39d2e8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.InputField.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79f4f2475e0b2c44e97ed1dee760627b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.cs new file mode 100644 index 00000000..362aa830 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.cs @@ -0,0 +1,130 @@ +#if UNITASK_TEXTMESHPRO_SUPPORT + +using System; +using System.Threading; +using TMPro; +using UnityEngine.Events; + +namespace Cysharp.Threading.Tasks +{ + public static partial class TextMeshProAsyncExtensions + { + // -> Text + public static void BindTo(this IUniTaskAsyncEnumerable source, TMP_Text text, bool rebindOnError = true) + { + BindToCore(source, text, text.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + public static void BindTo(this IUniTaskAsyncEnumerable source, TMP_Text text, CancellationToken cancellationToken, bool rebindOnError = true) + { + BindToCore(source, text, cancellationToken, rebindOnError).Forget(); + } + + static async UniTaskVoid BindToCore(IUniTaskAsyncEnumerable source, TMP_Text text, CancellationToken cancellationToken, bool rebindOnError) + { + var repeat = false; + BIND_AGAIN: + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + bool moveNext; + try + { + moveNext = await e.MoveNextAsync(); + repeat = false; + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + if (rebindOnError && !repeat) + { + repeat = true; + goto BIND_AGAIN; + } + else + { + throw; + } + } + + if (!moveNext) return; + + text.text = e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // -> Text + + public static void BindTo(this IUniTaskAsyncEnumerable source, TMP_Text text, bool rebindOnError = true) + { + BindToCore(source, text, text.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + public static void BindTo(this IUniTaskAsyncEnumerable source, TMP_Text text, CancellationToken cancellationToken, bool rebindOnError = true) + { + BindToCore(source, text, cancellationToken, rebindOnError).Forget(); + } + + public static void BindTo(this AsyncReactiveProperty source, TMP_Text text, bool rebindOnError = true) + { + BindToCore(source, text, text.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + static async UniTaskVoid BindToCore(IUniTaskAsyncEnumerable source, TMP_Text text, CancellationToken cancellationToken, bool rebindOnError) + { + var repeat = false; + BIND_AGAIN: + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + bool moveNext; + try + { + moveNext = await e.MoveNextAsync(); + repeat = false; + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + if (rebindOnError && !repeat) + { + repeat = true; + goto BIND_AGAIN; + } + else + { + throw; + } + } + + if (!moveNext) return; + + text.text = e.Current.ToString(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.cs.meta new file mode 100644 index 00000000..752d125c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/TextMeshProAsyncExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6ba480edafb67d4e91bb10feb64fae5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/UniTask.TextMeshPro.asmdef b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/UniTask.TextMeshPro.asmdef new file mode 100644 index 00000000..3ac90fb7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/UniTask.TextMeshPro.asmdef @@ -0,0 +1,27 @@ +{ + "name": "UniTask.TextMeshPro", + "references": [ + "UniTask", + "Unity.TextMeshPro" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.textmeshpro", + "expression": "", + "define": "UNITASK_TEXTMESHPRO_SUPPORT" + }, + { + "name": "com.unity.ugui", + "expression": "2.0.0", + "define": "UNITASK_TEXTMESHPRO_SUPPORT" + } + ], + "noEngineReferences": false +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/UniTask.TextMeshPro.asmdef.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/UniTask.TextMeshPro.asmdef.meta new file mode 100644 index 00000000..4b59831d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/External/TextMeshPro/UniTask.TextMeshPro.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: dc47925d1a5fa2946bdd37746b2b5d48 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskAsyncEnumerable.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskAsyncEnumerable.cs new file mode 100644 index 00000000..847d4305 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskAsyncEnumerable.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public interface IUniTaskAsyncEnumerable + { + IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default); + } + + public interface IUniTaskAsyncEnumerator : IUniTaskAsyncDisposable + { + T Current { get; } + UniTask MoveNextAsync(); + } + + public interface IUniTaskAsyncDisposable + { + UniTask DisposeAsync(); + } + + public interface IUniTaskOrderedAsyncEnumerable : IUniTaskAsyncEnumerable + { + IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func keySelector, IComparer comparer, bool descending); + IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending); + IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending); + } + + public interface IConnectableUniTaskAsyncEnumerable : IUniTaskAsyncEnumerable + { + IDisposable Connect(); + } + + // don't use AsyncGrouping. + //public interface IUniTaskAsyncGrouping : IUniTaskAsyncEnumerable + //{ + // TKey Key { get; } + //} + + public static class UniTaskAsyncEnumerableExtensions + { + public static UniTaskCancelableAsyncEnumerable WithCancellation(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + return new UniTaskCancelableAsyncEnumerable(source, cancellationToken); + } + } + + [StructLayout(LayoutKind.Auto)] + public readonly struct UniTaskCancelableAsyncEnumerable + { + private readonly IUniTaskAsyncEnumerable enumerable; + private readonly CancellationToken cancellationToken; + + internal UniTaskCancelableAsyncEnumerable(IUniTaskAsyncEnumerable enumerable, CancellationToken cancellationToken) + { + this.enumerable = enumerable; + this.cancellationToken = cancellationToken; + } + + public Enumerator GetAsyncEnumerator() + { + return new Enumerator(enumerable.GetAsyncEnumerator(cancellationToken)); + } + + [StructLayout(LayoutKind.Auto)] + public readonly struct Enumerator + { + private readonly IUniTaskAsyncEnumerator enumerator; + + internal Enumerator(IUniTaskAsyncEnumerator enumerator) + { + this.enumerator = enumerator; + } + + public T Current => enumerator.Current; + + public UniTask MoveNextAsync() + { + return enumerator.MoveNextAsync(); + } + + + public UniTask DisposeAsync() + { + return enumerator.DisposeAsync(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskAsyncEnumerable.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskAsyncEnumerable.cs.meta new file mode 100644 index 00000000..12f0fe52 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskAsyncEnumerable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b20cf9f02ac585948a4372fa4ee06504 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskSource.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskSource.cs new file mode 100644 index 00000000..ad758f1c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskSource.cs @@ -0,0 +1,127 @@ +#pragma warning disable CS1591 +#pragma warning disable CS0108 + +#if (UNITASK_NETCORE && !NETSTANDARD2_0) || UNITY_2022_3_OR_NEWER +#define SUPPORT_VALUETASK +#endif + +using System; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks +{ + public enum UniTaskStatus + { + /// The operation has not yet completed. + Pending = 0, + /// The operation completed successfully. + Succeeded = 1, + /// The operation completed with an error. + Faulted = 2, + /// The operation completed due to cancellation. + Canceled = 3 + } + + // similar as IValueTaskSource + public interface IUniTaskSource +#if SUPPORT_VALUETASK + : System.Threading.Tasks.Sources.IValueTaskSource +#endif + { + UniTaskStatus GetStatus(short token); + void OnCompleted(Action continuation, object state, short token); + void GetResult(short token); + + UniTaskStatus UnsafeGetStatus(); // only for debug use. + +#if SUPPORT_VALUETASK + + System.Threading.Tasks.Sources.ValueTaskSourceStatus System.Threading.Tasks.Sources.IValueTaskSource.GetStatus(short token) + { + return (System.Threading.Tasks.Sources.ValueTaskSourceStatus)(int)((IUniTaskSource)this).GetStatus(token); + } + + void System.Threading.Tasks.Sources.IValueTaskSource.GetResult(short token) + { + ((IUniTaskSource)this).GetResult(token); + } + + void System.Threading.Tasks.Sources.IValueTaskSource.OnCompleted(Action continuation, object state, short token, System.Threading.Tasks.Sources.ValueTaskSourceOnCompletedFlags flags) + { + // ignore flags, always none. + ((IUniTaskSource)this).OnCompleted(continuation, state, token); + } + +#endif + } + + public interface IUniTaskSource : IUniTaskSource +#if SUPPORT_VALUETASK + , System.Threading.Tasks.Sources.IValueTaskSource +#endif + { + new T GetResult(short token); + +#if SUPPORT_VALUETASK + + new public UniTaskStatus GetStatus(short token) + { + return ((IUniTaskSource)this).GetStatus(token); + } + + new public void OnCompleted(Action continuation, object state, short token) + { + ((IUniTaskSource)this).OnCompleted(continuation, state, token); + } + + System.Threading.Tasks.Sources.ValueTaskSourceStatus System.Threading.Tasks.Sources.IValueTaskSource.GetStatus(short token) + { + return (System.Threading.Tasks.Sources.ValueTaskSourceStatus)(int)((IUniTaskSource)this).GetStatus(token); + } + + T System.Threading.Tasks.Sources.IValueTaskSource.GetResult(short token) + { + return ((IUniTaskSource)this).GetResult(token); + } + + void System.Threading.Tasks.Sources.IValueTaskSource.OnCompleted(Action continuation, object state, short token, System.Threading.Tasks.Sources.ValueTaskSourceOnCompletedFlags flags) + { + // ignore flags, always none. + ((IUniTaskSource)this).OnCompleted(continuation, state, token); + } + +#endif + } + + public static class UniTaskStatusExtensions + { + /// status != Pending. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsCompleted(this UniTaskStatus status) + { + return status != UniTaskStatus.Pending; + } + + /// status == Succeeded. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsCompletedSuccessfully(this UniTaskStatus status) + { + return status == UniTaskStatus.Succeeded; + } + + /// status == Canceled. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsCanceled(this UniTaskStatus status) + { + return status == UniTaskStatus.Canceled; + } + + /// status == Faulted. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsFaulted(this UniTaskStatus status) + { + return status == UniTaskStatus.Faulted; + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskSource.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskSource.cs.meta new file mode 100644 index 00000000..b225d1c7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/IUniTaskSource.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3e4d023d8404ab742b5e808c98097c3c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal.meta new file mode 100644 index 00000000..8dd64bb2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 97a1a010309e85d4890f60a112211f93 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPool.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPool.cs new file mode 100644 index 00000000..e1d9d3b6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPool.cs @@ -0,0 +1,150 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Internal +{ + // Same interface as System.Buffers.ArrayPool but only provides Shared. + + internal sealed class ArrayPool + { + // Same size as System.Buffers.DefaultArrayPool + const int DefaultMaxNumberOfArraysPerBucket = 50; + + static readonly T[] EmptyArray = new T[0]; + + public static readonly ArrayPool Shared = new ArrayPool(); + + readonly MinimumQueue[] buckets; + readonly SpinLock[] locks; + + ArrayPool() + { + // see: GetQueueIndex + buckets = new MinimumQueue[18]; + locks = new SpinLock[18]; + for (int i = 0; i < buckets.Length; i++) + { + buckets[i] = new MinimumQueue(4); + locks[i] = new SpinLock(false); + } + } + + public T[] Rent(int minimumLength) + { + if (minimumLength < 0) + { + throw new ArgumentOutOfRangeException("minimumLength"); + } + else if (minimumLength == 0) + { + return EmptyArray; + } + + var size = CalculateSize(minimumLength); + var index = GetQueueIndex(size); + if (index != -1) + { + var q = buckets[index]; + var lockTaken = false; + try + { + locks[index].Enter(ref lockTaken); + + if (q.Count != 0) + { + return q.Dequeue(); + } + } + finally + { + if (lockTaken) locks[index].Exit(false); + } + } + + return new T[size]; + } + + public void Return(T[] array, bool clearArray = false) + { + if (array == null || array.Length == 0) + { + return; + } + + var index = GetQueueIndex(array.Length); + if (index != -1) + { + if (clearArray) + { + Array.Clear(array, 0, array.Length); + } + + var q = buckets[index]; + var lockTaken = false; + + try + { + locks[index].Enter(ref lockTaken); + + if (q.Count > DefaultMaxNumberOfArraysPerBucket) + { + return; + } + + q.Enqueue(array); + } + finally + { + if (lockTaken) locks[index].Exit(false); + } + } + } + + static int CalculateSize(int size) + { + size--; + size |= size >> 1; + size |= size >> 2; + size |= size >> 4; + size |= size >> 8; + size |= size >> 16; + size += 1; + + if (size < 8) + { + size = 8; + } + + return size; + } + + static int GetQueueIndex(int size) + { + switch (size) + { + case 8: return 0; + case 16: return 1; + case 32: return 2; + case 64: return 3; + case 128: return 4; + case 256: return 5; + case 512: return 6; + case 1024: return 7; + case 2048: return 8; + case 4096: return 9; + case 8192: return 10; + case 16384: return 11; + case 32768: return 12; + case 65536: return 13; + case 131072: return 14; + case 262144: return 15; + case 524288: return 16; + case 1048576: return 17; // max array length + default: + return -1; + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPool.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPool.cs.meta new file mode 100644 index 00000000..693816cc --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPool.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f83ebad81fb89fb4882331616ca6d248 +timeCreated: 1532361008 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPoolUtil.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPoolUtil.cs new file mode 100644 index 00000000..016901db --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPoolUtil.cs @@ -0,0 +1,115 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class ArrayPoolUtil + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void EnsureCapacity(ref T[] array, int index, ArrayPool pool) + { + if (array.Length <= index) + { + EnsureCapacityCore(ref array, index, pool); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void EnsureCapacityCore(ref T[] array, int index, ArrayPool pool) + { + if (array.Length <= index) + { + var newSize = array.Length * 2; + var newArray = pool.Rent((index < newSize) ? newSize : (index * 2)); + Array.Copy(array, 0, newArray, 0, array.Length); + + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + array = newArray; + } + } + + public static RentArray Materialize(IEnumerable source) + { + if (source is T[] array) + { + return new RentArray(array, array.Length, null); + } + + var defaultCount = 32; + if (source is ICollection coll) + { + if (coll.Count == 0) + { + return new RentArray(Array.Empty(), 0, null); + } + + defaultCount = coll.Count; + var pool = ArrayPool.Shared; + var buffer = pool.Rent(defaultCount); + coll.CopyTo(buffer, 0); + return new RentArray(buffer, coll.Count, pool); + } + else if (source is IReadOnlyCollection rcoll) + { + defaultCount = rcoll.Count; + } + + if (defaultCount == 0) + { + return new RentArray(Array.Empty(), 0, null); + } + + { + var pool = ArrayPool.Shared; + + var index = 0; + var buffer = pool.Rent(defaultCount); + foreach (var item in source) + { + EnsureCapacity(ref buffer, index, pool); + buffer[index++] = item; + } + + return new RentArray(buffer, index, pool); + } + } + + public struct RentArray : IDisposable + { + public readonly T[] Array; + public readonly int Length; + ArrayPool pool; + + public RentArray(T[] array, int length, ArrayPool pool) + { + this.Array = array; + this.Length = length; + this.pool = pool; + } + + public void Dispose() + { + DisposeManually(!RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + } + + public void DisposeManually(bool clearArray) + { + if (pool != null) + { + if (clearArray) + { + System.Array.Clear(Array, 0, Length); + } + + pool.Return(Array, clearArray: false); + pool = null; + } + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPoolUtil.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPoolUtil.cs.meta new file mode 100644 index 00000000..e06ec652 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayPoolUtil.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 424cc208fb61d4e448b08fcfa0eee25e +timeCreated: 1532361007 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayUtil.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayUtil.cs new file mode 100644 index 00000000..fc7a808c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayUtil.cs @@ -0,0 +1,73 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class ArrayUtil + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void EnsureCapacity(ref T[] array, int index) + { + if (array.Length <= index) + { + EnsureCore(ref array, index); + } + } + + // rare case, no inlining. + [MethodImpl(MethodImplOptions.NoInlining)] + static void EnsureCore(ref T[] array, int index) + { + var newSize = array.Length * 2; + var newArray = new T[(index < newSize) ? newSize : (index * 2)]; + Array.Copy(array, 0, newArray, 0, array.Length); + + array = newArray; + } + + /// + /// Optimizing utility to avoid .ToArray() that creates buffer copy(cut to just size). + /// + public static (T[] array, int length) Materialize(IEnumerable source) + { + if (source is T[] array) + { + return (array, array.Length); + } + + var defaultCount = 4; + if (source is ICollection coll) + { + defaultCount = coll.Count; + var buffer = new T[defaultCount]; + coll.CopyTo(buffer, 0); + return (buffer, defaultCount); + } + else if (source is IReadOnlyCollection rcoll) + { + defaultCount = rcoll.Count; + } + + if (defaultCount == 0) + { + return (Array.Empty(), 0); + } + + { + var index = 0; + var buffer = new T[defaultCount]; + foreach (var item in source) + { + EnsureCapacity(ref buffer, index); + buffer[index++] = item; + } + + return (buffer, index); + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayUtil.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayUtil.cs.meta new file mode 100644 index 00000000..645fc4ed --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ArrayUtil.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 23146a82ec99f2542a87971c8d3d7988 +timeCreated: 1532361007 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ContinuationQueue.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ContinuationQueue.cs new file mode 100644 index 00000000..a3111268 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ContinuationQueue.cs @@ -0,0 +1,225 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal sealed class ContinuationQueue + { + const int MaxArrayLength = 0X7FEFFFFF; + const int InitialSize = 16; + + readonly PlayerLoopTiming timing; + + SpinLock gate = new SpinLock(false); + bool dequing = false; + + int actionListCount = 0; + Action[] actionList = new Action[InitialSize]; + + int waitingListCount = 0; + Action[] waitingList = new Action[InitialSize]; + + public ContinuationQueue(PlayerLoopTiming timing) + { + this.timing = timing; + } + + public void Enqueue(Action continuation) + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + + if (dequing) + { + // Ensure Capacity + if (waitingList.Length == waitingListCount) + { + var newLength = waitingListCount * 2; + if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength; + + var newArray = new Action[newLength]; + Array.Copy(waitingList, newArray, waitingListCount); + waitingList = newArray; + } + waitingList[waitingListCount] = continuation; + waitingListCount++; + } + else + { + // Ensure Capacity + if (actionList.Length == actionListCount) + { + var newLength = actionListCount * 2; + if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength; + + var newArray = new Action[newLength]; + Array.Copy(actionList, newArray, actionListCount); + actionList = newArray; + } + actionList[actionListCount] = continuation; + actionListCount++; + } + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + public int Clear() + { + var rest = actionListCount + waitingListCount; + + actionListCount = 0; + actionList = new Action[InitialSize]; + + waitingListCount = 0; + waitingList = new Action[InitialSize]; + + return rest; + } + + // delegate entrypoint. + public void Run() + { + // for debugging, create named stacktrace. +#if DEBUG + switch (timing) + { + case PlayerLoopTiming.Initialization: + Initialization(); + break; + case PlayerLoopTiming.LastInitialization: + LastInitialization(); + break; + case PlayerLoopTiming.EarlyUpdate: + EarlyUpdate(); + break; + case PlayerLoopTiming.LastEarlyUpdate: + LastEarlyUpdate(); + break; + case PlayerLoopTiming.FixedUpdate: + FixedUpdate(); + break; + case PlayerLoopTiming.LastFixedUpdate: + LastFixedUpdate(); + break; + case PlayerLoopTiming.PreUpdate: + PreUpdate(); + break; + case PlayerLoopTiming.LastPreUpdate: + LastPreUpdate(); + break; + case PlayerLoopTiming.Update: + Update(); + break; + case PlayerLoopTiming.LastUpdate: + LastUpdate(); + break; + case PlayerLoopTiming.PreLateUpdate: + PreLateUpdate(); + break; + case PlayerLoopTiming.LastPreLateUpdate: + LastPreLateUpdate(); + break; + case PlayerLoopTiming.PostLateUpdate: + PostLateUpdate(); + break; + case PlayerLoopTiming.LastPostLateUpdate: + LastPostLateUpdate(); + break; +#if UNITY_2020_2_OR_NEWER + case PlayerLoopTiming.TimeUpdate: + TimeUpdate(); + break; + case PlayerLoopTiming.LastTimeUpdate: + LastTimeUpdate(); + break; +#endif + default: + break; + } +#else + RunCore(); +#endif + } + + void Initialization() => RunCore(); + void LastInitialization() => RunCore(); + void EarlyUpdate() => RunCore(); + void LastEarlyUpdate() => RunCore(); + void FixedUpdate() => RunCore(); + void LastFixedUpdate() => RunCore(); + void PreUpdate() => RunCore(); + void LastPreUpdate() => RunCore(); + void Update() => RunCore(); + void LastUpdate() => RunCore(); + void PreLateUpdate() => RunCore(); + void LastPreLateUpdate() => RunCore(); + void PostLateUpdate() => RunCore(); + void LastPostLateUpdate() => RunCore(); +#if UNITY_2020_2_OR_NEWER + void TimeUpdate() => RunCore(); + void LastTimeUpdate() => RunCore(); +#endif + + [System.Diagnostics.DebuggerHidden] + void RunCore() + { + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + if (actionListCount == 0) return; + dequing = true; + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + for (int i = 0; i < actionListCount; i++) + { + + var action = actionList[i]; + actionList[i] = null; + try + { + action(); + } + catch (Exception ex) + { + UnityEngine.Debug.LogException(ex); + } + } + + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + dequing = false; + + var swapTempActionList = actionList; + + actionListCount = waitingListCount; + actionList = waitingList; + + waitingListCount = 0; + waitingList = swapTempActionList; + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ContinuationQueue.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ContinuationQueue.cs.meta new file mode 100644 index 00000000..b04e5418 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ContinuationQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f66c32454e50f2546b17deadc80a4c77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/DiagnosticsExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/DiagnosticsExtensions.cs new file mode 100644 index 00000000..77d998fb --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/DiagnosticsExtensions.cs @@ -0,0 +1,249 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class DiagnosticsExtensions + { + static bool displayFilenames = true; + + static readonly Regex typeBeautifyRegex = new Regex("`.+$", RegexOptions.Compiled); + + static readonly Dictionary builtInTypeNames = new Dictionary + { + { typeof(void), "void" }, + { typeof(bool), "bool" }, + { typeof(byte), "byte" }, + { typeof(char), "char" }, + { typeof(decimal), "decimal" }, + { typeof(double), "double" }, + { typeof(float), "float" }, + { typeof(int), "int" }, + { typeof(long), "long" }, + { typeof(object), "object" }, + { typeof(sbyte), "sbyte" }, + { typeof(short), "short" }, + { typeof(string), "string" }, + { typeof(uint), "uint" }, + { typeof(ulong), "ulong" }, + { typeof(ushort), "ushort" }, + { typeof(Task), "Task" }, + { typeof(UniTask), "UniTask" }, + { typeof(UniTaskVoid), "UniTaskVoid" } + }; + + public static string CleanupAsyncStackTrace(this StackTrace stackTrace) + { + if (stackTrace == null) return ""; + + var sb = new StringBuilder(); + for (int i = 0; i < stackTrace.FrameCount; i++) + { + var sf = stackTrace.GetFrame(i); + + var mb = sf.GetMethod(); + + if (IgnoreLine(mb)) continue; + if (IsAsync(mb)) + { + sb.Append("async "); + TryResolveStateMachineMethod(ref mb, out var decType); + } + + // return type + if (mb is MethodInfo mi) + { + sb.Append(BeautifyType(mi.ReturnType, false)); + sb.Append(" "); + } + + // method name + sb.Append(BeautifyType(mb.DeclaringType, false)); + if (!mb.IsConstructor) + { + sb.Append("."); + } + sb.Append(mb.Name); + if (mb.IsGenericMethod) + { + sb.Append("<"); + foreach (var item in mb.GetGenericArguments()) + { + sb.Append(BeautifyType(item, true)); + } + sb.Append(">"); + } + + // parameter + sb.Append("("); + sb.Append(string.Join(", ", mb.GetParameters().Select(p => BeautifyType(p.ParameterType, true) + " " + p.Name))); + sb.Append(")"); + + // file name + if (displayFilenames && (sf.GetILOffset() != -1)) + { + String fileName = null; + + try + { + fileName = sf.GetFileName(); + } + catch (NotSupportedException) + { + displayFilenames = false; + } + catch (SecurityException) + { + displayFilenames = false; + } + + if (fileName != null) + { + sb.Append(' '); + sb.AppendFormat(CultureInfo.InvariantCulture, "(at {0})", AppendHyperLink(fileName, sf.GetFileLineNumber().ToString())); + } + } + + sb.AppendLine(); + } + return sb.ToString(); + } + + + static bool IsAsync(MethodBase methodInfo) + { + var declareType = methodInfo.DeclaringType; + return typeof(IAsyncStateMachine).IsAssignableFrom(declareType); + } + + // code from Ben.Demystifier/EnhancedStackTrace.Frame.cs + static bool TryResolveStateMachineMethod(ref MethodBase method, out Type declaringType) + { + declaringType = method.DeclaringType; + + var parentType = declaringType.DeclaringType; + if (parentType == null) + { + return false; + } + + var methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); + if (methods == null) + { + return false; + } + + foreach (var candidateMethod in methods) + { + var attributes = candidateMethod.GetCustomAttributes(false); + if (attributes == null) + { + continue; + } + + foreach (var asma in attributes) + { + if (asma.StateMachineType == declaringType) + { + method = candidateMethod; + declaringType = candidateMethod.DeclaringType; + // Mark the iterator as changed; so it gets the + annotation of the original method + // async statemachines resolve directly to their builder methods so aren't marked as changed + return asma is IteratorStateMachineAttribute; + } + } + } + + return false; + } + + static string BeautifyType(Type t, bool shortName) + { + if (builtInTypeNames.TryGetValue(t, out var builtin)) + { + return builtin; + } + if (t.IsGenericParameter) return t.Name; + if (t.IsArray) return BeautifyType(t.GetElementType(), shortName) + "[]"; + if (t.FullName?.StartsWith("System.ValueTuple") ?? false) + { + return "(" + string.Join(", ", t.GetGenericArguments().Select(x => BeautifyType(x, true))) + ")"; + } + if (!t.IsGenericType) return shortName ? t.Name : t.FullName.Replace("Cysharp.Threading.Tasks.Triggers.", "").Replace("Cysharp.Threading.Tasks.Internal.", "").Replace("Cysharp.Threading.Tasks.", "") ?? t.Name; + + var innerFormat = string.Join(", ", t.GetGenericArguments().Select(x => BeautifyType(x, true))); + + var genericType = t.GetGenericTypeDefinition().FullName; + if (genericType == "System.Threading.Tasks.Task`1") + { + genericType = "Task"; + } + + return typeBeautifyRegex.Replace(genericType, "").Replace("Cysharp.Threading.Tasks.Triggers.", "").Replace("Cysharp.Threading.Tasks.Internal.", "").Replace("Cysharp.Threading.Tasks.", "") + "<" + innerFormat + ">"; + } + + static bool IgnoreLine(MethodBase methodInfo) + { + var declareType = methodInfo.DeclaringType.FullName; + if (declareType == "System.Threading.ExecutionContext") + { + return true; + } + else if (declareType.StartsWith("System.Runtime.CompilerServices")) + { + return true; + } + else if (declareType.StartsWith("Cysharp.Threading.Tasks.CompilerServices")) + { + return true; + } + else if (declareType == "System.Threading.Tasks.AwaitTaskContinuation") + { + return true; + } + else if (declareType.StartsWith("System.Threading.Tasks.Task")) + { + return true; + } + else if (declareType.StartsWith("Cysharp.Threading.Tasks.UniTaskCompletionSourceCore")) + { + return true; + } + else if (declareType.StartsWith("Cysharp.Threading.Tasks.AwaiterActions")) + { + return true; + } + + return false; + } + + static string AppendHyperLink(string path, string line) + { + var fi = new FileInfo(path); + if (fi.Directory == null) + { + return fi.Name; + } + else + { + var fname = fi.FullName.Replace(Path.DirectorySeparatorChar, '/').Replace(PlayerLoopHelper.ApplicationDataPath, ""); + var withAssetsPath = "Assets/" + fname; + return "" + withAssetsPath + ":" + line + ""; + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/DiagnosticsExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/DiagnosticsExtensions.cs.meta new file mode 100644 index 00000000..6c1f06c2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/DiagnosticsExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f80fb1c9ed4c99447be1b0a47a8d980b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/Error.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/Error.cs new file mode 100644 index 00000000..9664491e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/Error.cs @@ -0,0 +1,79 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class Error + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ThrowArgumentNullException(T value, string paramName) + where T : class + { + if (value == null) ThrowArgumentNullExceptionCore(paramName); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void ThrowArgumentNullExceptionCore(string paramName) + { + throw new ArgumentNullException(paramName); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception ArgumentOutOfRange(string paramName) + { + return new ArgumentOutOfRangeException(paramName); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception NoElements() + { + return new InvalidOperationException("Source sequence doesn't contain any elements."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception MoreThanOneElement() + { + return new InvalidOperationException("Source sequence contains more than one element."); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentException(string message) + { + throw new ArgumentException(message); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowNotYetCompleted() + { + throw new InvalidOperationException("Not yet completed."); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static T ThrowNotYetCompleted() + { + throw new InvalidOperationException("Not yet completed."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ThrowWhenContinuationIsAlreadyRegistered(T continuationField) + where T : class + { + if (continuationField != null) ThrowInvalidOperationExceptionCore("continuation is already registered."); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void ThrowInvalidOperationExceptionCore(string message) + { + throw new InvalidOperationException(message); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowOperationCanceledException() + { + throw new OperationCanceledException(); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/Error.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/Error.cs.meta new file mode 100644 index 00000000..2e5d219a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/Error.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5f39f495294d4604b8082202faf98554 +timeCreated: 1532361007 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/MinimumQueue.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/MinimumQueue.cs new file mode 100644 index 00000000..a6b567ad --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/MinimumQueue.cs @@ -0,0 +1,112 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.Internal +{ + // optimized version of Standard Queue. + internal class MinimumQueue + { + const int MinimumGrow = 4; + const int GrowFactor = 200; + + T[] array; + int head; + int tail; + int size; + + public MinimumQueue(int capacity) + { + if (capacity < 0) throw new ArgumentOutOfRangeException("capacity"); + array = new T[capacity]; + head = tail = size = 0; + } + + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get { return size; } + } + + public T Peek() + { + if (size == 0) ThrowForEmptyQueue(); + return array[head]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Enqueue(T item) + { + if (size == array.Length) + { + Grow(); + } + + array[tail] = item; + MoveNext(ref tail); + size++; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Dequeue() + { + if (size == 0) ThrowForEmptyQueue(); + + int head = this.head; + T[] array = this.array; + T removed = array[head]; + array[head] = default(T); + MoveNext(ref this.head); + size--; + return removed; + } + + void Grow() + { + int newcapacity = (int)((long)array.Length * (long)GrowFactor / 100); + if (newcapacity < array.Length + MinimumGrow) + { + newcapacity = array.Length + MinimumGrow; + } + SetCapacity(newcapacity); + } + + void SetCapacity(int capacity) + { + T[] newarray = new T[capacity]; + if (size > 0) + { + if (head < tail) + { + Array.Copy(array, head, newarray, 0, size); + } + else + { + Array.Copy(array, head, newarray, 0, array.Length - head); + Array.Copy(array, 0, newarray, array.Length - head, tail); + } + } + + array = newarray; + head = 0; + tail = (size == capacity) ? 0 : size; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void MoveNext(ref int index) + { + int tmp = index + 1; + if (tmp == array.Length) + { + tmp = 0; + } + index = tmp; + } + + void ThrowForEmptyQueue() + { + throw new InvalidOperationException("EmptyQueue"); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/MinimumQueue.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/MinimumQueue.cs.meta new file mode 100644 index 00000000..dc067367 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/MinimumQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d63add489ccc99498114d79702b904d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs new file mode 100644 index 00000000..43625ab5 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs @@ -0,0 +1,260 @@ + +using System; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal sealed class PlayerLoopRunner + { + const int InitialSize = 16; + + readonly PlayerLoopTiming timing; + readonly object runningAndQueueLock = new object(); + readonly object arrayLock = new object(); + readonly Action unhandledExceptionCallback; + + int tail = 0; + bool running = false; + IPlayerLoopItem[] loopItems = new IPlayerLoopItem[InitialSize]; + MinimumQueue waitQueue = new MinimumQueue(InitialSize); + + + + public PlayerLoopRunner(PlayerLoopTiming timing) + { + this.unhandledExceptionCallback = ex => Debug.LogException(ex); + this.timing = timing; + } + + public void AddAction(IPlayerLoopItem item) + { + lock (runningAndQueueLock) + { + if (running) + { + waitQueue.Enqueue(item); + return; + } + } + + lock (arrayLock) + { + // Ensure Capacity + if (loopItems.Length == tail) + { + Array.Resize(ref loopItems, checked(tail * 2)); + } + loopItems[tail++] = item; + } + } + + public int Clear() + { + lock (arrayLock) + { + var rest = 0; + + for (var index = 0; index < loopItems.Length; index++) + { + if (loopItems[index] != null) + { + rest++; + } + + loopItems[index] = null; + } + + tail = 0; + return rest; + } + } + + // delegate entrypoint. + public void Run() + { + // for debugging, create named stacktrace. +#if DEBUG + switch (timing) + { + case PlayerLoopTiming.Initialization: + Initialization(); + break; + case PlayerLoopTiming.LastInitialization: + LastInitialization(); + break; + case PlayerLoopTiming.EarlyUpdate: + EarlyUpdate(); + break; + case PlayerLoopTiming.LastEarlyUpdate: + LastEarlyUpdate(); + break; + case PlayerLoopTiming.FixedUpdate: + FixedUpdate(); + break; + case PlayerLoopTiming.LastFixedUpdate: + LastFixedUpdate(); + break; + case PlayerLoopTiming.PreUpdate: + PreUpdate(); + break; + case PlayerLoopTiming.LastPreUpdate: + LastPreUpdate(); + break; + case PlayerLoopTiming.Update: + Update(); + break; + case PlayerLoopTiming.LastUpdate: + LastUpdate(); + break; + case PlayerLoopTiming.PreLateUpdate: + PreLateUpdate(); + break; + case PlayerLoopTiming.LastPreLateUpdate: + LastPreLateUpdate(); + break; + case PlayerLoopTiming.PostLateUpdate: + PostLateUpdate(); + break; + case PlayerLoopTiming.LastPostLateUpdate: + LastPostLateUpdate(); + break; +#if UNITY_2020_2_OR_NEWER + case PlayerLoopTiming.TimeUpdate: + TimeUpdate(); + break; + case PlayerLoopTiming.LastTimeUpdate: + LastTimeUpdate(); + break; +#endif + default: + break; + } +#else + RunCore(); +#endif + } + + void Initialization() => RunCore(); + void LastInitialization() => RunCore(); + void EarlyUpdate() => RunCore(); + void LastEarlyUpdate() => RunCore(); + void FixedUpdate() => RunCore(); + void LastFixedUpdate() => RunCore(); + void PreUpdate() => RunCore(); + void LastPreUpdate() => RunCore(); + void Update() => RunCore(); + void LastUpdate() => RunCore(); + void PreLateUpdate() => RunCore(); + void LastPreLateUpdate() => RunCore(); + void PostLateUpdate() => RunCore(); + void LastPostLateUpdate() => RunCore(); +#if UNITY_2020_2_OR_NEWER + void TimeUpdate() => RunCore(); + void LastTimeUpdate() => RunCore(); +#endif + + [System.Diagnostics.DebuggerHidden] + void RunCore() + { + lock (runningAndQueueLock) + { + running = true; + } + + lock (arrayLock) + { + var j = tail - 1; + + for (int i = 0; i < loopItems.Length; i++) + { + var action = loopItems[i]; + if (action != null) + { + try + { + if (!action.MoveNext()) + { + loopItems[i] = null; + } + else + { + continue; // next i + } + } + catch (Exception ex) + { + loopItems[i] = null; + try + { + unhandledExceptionCallback(ex); + } + catch { } + } + } + + // find null, loop from tail + while (i < j) + { + var fromTail = loopItems[j]; + if (fromTail != null) + { + try + { + if (!fromTail.MoveNext()) + { + loopItems[j] = null; + j--; + continue; // next j + } + else + { + // swap + loopItems[i] = fromTail; + loopItems[j] = null; + j--; + goto NEXT_LOOP; // next i + } + } + catch (Exception ex) + { + loopItems[j] = null; + j--; + try + { + unhandledExceptionCallback(ex); + } + catch { } + continue; // next j + } + } + else + { + j--; + } + } + + tail = i; // loop end + break; // LOOP END + + NEXT_LOOP: + continue; + } + + + lock (runningAndQueueLock) + { + running = false; + while (waitQueue.Count != 0) + { + if (loopItems.Length == tail) + { + Array.Resize(ref loopItems, checked(tail * 2)); + } + loopItems[tail++] = waitQueue.Dequeue(); + } + } + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs.meta new file mode 100644 index 00000000..603dbc93 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 340c6d420bb4f484aa8683415ea92571 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PooledDelegate.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PooledDelegate.cs new file mode 100644 index 00000000..518244fe --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PooledDelegate.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal sealed class PooledDelegate : ITaskPoolNode> + { + static TaskPool> pool; + + PooledDelegate nextNode; + public ref PooledDelegate NextNode => ref nextNode; + + static PooledDelegate() + { + TaskPool.RegisterSizeGetter(typeof(PooledDelegate), () => pool.Size); + } + + readonly Action runDelegate; + Action continuation; + + PooledDelegate() + { + runDelegate = Run; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Action Create(Action continuation) + { + if (!pool.TryPop(out var item)) + { + item = new PooledDelegate(); + } + + item.continuation = continuation; + return item.runDelegate; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void Run(T _) + { + var call = continuation; + continuation = null; + if (call != null) + { + pool.TryPush(this); + call.Invoke(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PooledDelegate.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PooledDelegate.cs.meta new file mode 100644 index 00000000..7f92aff4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/PooledDelegate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8932579438742fa40b010edd412dbfba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/RuntimeHelpersAbstraction.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/RuntimeHelpersAbstraction.cs new file mode 100644 index 00000000..cbabdab1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/RuntimeHelpersAbstraction.cs @@ -0,0 +1,64 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +#if UNITY_2018_3_OR_NEWER +using UnityEngine; +#endif + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class RuntimeHelpersAbstraction + { + // If we can use RuntimeHelpers.IsReferenceOrContainsReferences(.NET Core 2.0), use it. + public static bool IsWellKnownNoReferenceContainsType() + { + return WellKnownNoReferenceContainsType.IsWellKnownType; + } + + static bool WellKnownNoReferenceContainsTypeInitialize(Type t) + { + // The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single. + if (t.IsPrimitive) return true; + + if (t.IsEnum) return true; + if (t == typeof(DateTime)) return true; + if (t == typeof(DateTimeOffset)) return true; + if (t == typeof(Guid)) return true; + if (t == typeof(decimal)) return true; + + // unwrap nullable + if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return WellKnownNoReferenceContainsTypeInitialize(t.GetGenericArguments()[0]); + } + +#if UNITY_2018_3_OR_NEWER + + // or add other wellknown types(Vector, etc...) here + if (t == typeof(Vector2)) return true; + if (t == typeof(Vector3)) return true; + if (t == typeof(Vector4)) return true; + if (t == typeof(Color)) return true; + if (t == typeof(Rect)) return true; + if (t == typeof(Bounds)) return true; + if (t == typeof(Quaternion)) return true; + if (t == typeof(Vector2Int)) return true; + if (t == typeof(Vector3Int)) return true; + +#endif + + return false; + } + + static class WellKnownNoReferenceContainsType + { + public static readonly bool IsWellKnownType; + + static WellKnownNoReferenceContainsType() + { + IsWellKnownType = WellKnownNoReferenceContainsTypeInitialize(typeof(T)); + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/RuntimeHelpersAbstraction.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/RuntimeHelpersAbstraction.cs.meta new file mode 100644 index 00000000..42543911 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/RuntimeHelpersAbstraction.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 94975e4d4e0c0ea4ba787d3872ce9bb4 +timeCreated: 1532361007 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/StatePool.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/StatePool.cs new file mode 100644 index 00000000..e1d40bd7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/StatePool.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class StateTuple + { + public static StateTuple Create(T1 item1) + { + return StatePool.Create(item1); + } + + public static StateTuple Create(T1 item1, T2 item2) + { + return StatePool.Create(item1, item2); + } + + public static StateTuple Create(T1 item1, T2 item2, T3 item3) + { + return StatePool.Create(item1, item2, item3); + } + } + + internal class StateTuple : IDisposable + { + public T1 Item1; + + public void Deconstruct(out T1 item1) + { + item1 = this.Item1; + } + + public void Dispose() + { + StatePool.Return(this); + } + } + + internal static class StatePool + { + static readonly ConcurrentQueue> queue = new ConcurrentQueue>(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static StateTuple Create(T1 item1) + { + if (queue.TryDequeue(out var value)) + { + value.Item1 = item1; + return value; + } + + return new StateTuple { Item1 = item1 }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(StateTuple tuple) + { + tuple.Item1 = default; + queue.Enqueue(tuple); + } + } + + internal class StateTuple : IDisposable + { + public T1 Item1; + public T2 Item2; + + public void Deconstruct(out T1 item1, out T2 item2) + { + item1 = this.Item1; + item2 = this.Item2; + } + + public void Dispose() + { + StatePool.Return(this); + } + } + + internal static class StatePool + { + static readonly ConcurrentQueue> queue = new ConcurrentQueue>(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static StateTuple Create(T1 item1, T2 item2) + { + if (queue.TryDequeue(out var value)) + { + value.Item1 = item1; + value.Item2 = item2; + return value; + } + + return new StateTuple { Item1 = item1, Item2 = item2 }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(StateTuple tuple) + { + tuple.Item1 = default; + tuple.Item2 = default; + queue.Enqueue(tuple); + } + } + + internal class StateTuple : IDisposable + { + public T1 Item1; + public T2 Item2; + public T3 Item3; + + public void Deconstruct(out T1 item1, out T2 item2, out T3 item3) + { + item1 = this.Item1; + item2 = this.Item2; + item3 = this.Item3; + } + + public void Dispose() + { + StatePool.Return(this); + } + } + + internal static class StatePool + { + static readonly ConcurrentQueue> queue = new ConcurrentQueue>(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static StateTuple Create(T1 item1, T2 item2, T3 item3) + { + if (queue.TryDequeue(out var value)) + { + value.Item1 = item1; + value.Item2 = item2; + value.Item3 = item3; + return value; + } + + return new StateTuple { Item1 = item1, Item2 = item2, Item3 = item3 }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(StateTuple tuple) + { + tuple.Item1 = default; + tuple.Item2 = default; + tuple.Item3 = default; + queue.Enqueue(tuple); + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/StatePool.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/StatePool.cs.meta new file mode 100644 index 00000000..6779aa1e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/StatePool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 60cdf0bcaea36b444a7ae7263ae7598f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/TaskTracker.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/TaskTracker.cs new file mode 100644 index 00000000..c163e22d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/TaskTracker.cs @@ -0,0 +1,178 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + // public for add user custom. + + public static class TaskTracker + { +#if UNITY_EDITOR + + static int trackingId = 0; + + public const string EnableAutoReloadKey = "UniTaskTrackerWindow_EnableAutoReloadKey"; + public const string EnableTrackingKey = "UniTaskTrackerWindow_EnableTrackingKey"; + public const string EnableStackTraceKey = "UniTaskTrackerWindow_EnableStackTraceKey"; + + public static class EditorEnableState + { + static bool enableAutoReload; + public static bool EnableAutoReload + { + get { return enableAutoReload; } + set + { + enableAutoReload = value; + UnityEditor.EditorPrefs.SetBool(EnableAutoReloadKey, value); + } + } + + static bool enableTracking; + public static bool EnableTracking + { + get { return enableTracking; } + set + { + enableTracking = value; + UnityEditor.EditorPrefs.SetBool(EnableTrackingKey, value); + } + } + + static bool enableStackTrace; + public static bool EnableStackTrace + { + get { return enableStackTrace; } + set + { + enableStackTrace = value; + UnityEditor.EditorPrefs.SetBool(EnableStackTraceKey, value); + } + } + } + +#endif + + + static List> listPool = new List>(); + + static readonly WeakDictionary tracking = new WeakDictionary(); + + [Conditional("UNITY_EDITOR")] + public static void TrackActiveTask(IUniTaskSource task, int skipFrame) + { +#if UNITY_EDITOR + dirty = true; + if (!EditorEnableState.EnableTracking) return; + var stackTrace = EditorEnableState.EnableStackTrace ? new StackTrace(skipFrame, true).CleanupAsyncStackTrace() : ""; + + string typeName; + if (EditorEnableState.EnableStackTrace) + { + var sb = new StringBuilder(); + TypeBeautify(task.GetType(), sb); + typeName = sb.ToString(); + } + else + { + typeName = task.GetType().Name; + } + tracking.TryAdd(task, (typeName, Interlocked.Increment(ref trackingId), DateTime.UtcNow, stackTrace)); +#endif + } + + [Conditional("UNITY_EDITOR")] + public static void RemoveTracking(IUniTaskSource task) + { +#if UNITY_EDITOR + dirty = true; + if (!EditorEnableState.EnableTracking) return; + var success = tracking.TryRemove(task); +#endif + } + + static bool dirty; + + public static bool CheckAndResetDirty() + { + var current = dirty; + dirty = false; + return current; + } + + /// (trackingId, awaiterType, awaiterStatus, createdTime, stackTrace) + public static void ForEachActiveTask(Action action) + { + lock (listPool) + { + var count = tracking.ToList(ref listPool, clear: false); + try + { + for (int i = 0; i < count; i++) + { + action(listPool[i].Value.trackingId, listPool[i].Value.formattedType, listPool[i].Key.UnsafeGetStatus(), listPool[i].Value.addTime, listPool[i].Value.stackTrace); + listPool[i] = default; + } + } + catch + { + listPool.Clear(); + throw; + } + } + } + + static void TypeBeautify(Type type, StringBuilder sb) + { + if (type.IsNested) + { + // TypeBeautify(type.DeclaringType, sb); + sb.Append(type.DeclaringType.Name.ToString()); + sb.Append("."); + } + + if (type.IsGenericType) + { + var genericsStart = type.Name.IndexOf("`"); + if (genericsStart != -1) + { + sb.Append(type.Name.Substring(0, genericsStart)); + } + else + { + sb.Append(type.Name); + } + sb.Append("<"); + var first = true; + foreach (var item in type.GetGenericArguments()) + { + if (!first) + { + sb.Append(", "); + } + first = false; + TypeBeautify(item, sb); + } + sb.Append(">"); + } + else + { + sb.Append(type.Name); + } + } + + //static string RemoveUniTaskNamespace(string str) + //{ + // return str.Replace("Cysharp.Threading.Tasks.CompilerServices", "") + // .Replace("Cysharp.Threading.Tasks.Linq", "") + // .Replace("Cysharp.Threading.Tasks", ""); + //} + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/TaskTracker.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/TaskTracker.cs.meta new file mode 100644 index 00000000..5563bf78 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/TaskTracker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a203c73eb4ccdbb44bddfd82d38fdda9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs new file mode 100644 index 00000000..906f3b6a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal static class UnityEqualityComparer + { + public static readonly IEqualityComparer Vector2 = new Vector2EqualityComparer(); + public static readonly IEqualityComparer Vector3 = new Vector3EqualityComparer(); + public static readonly IEqualityComparer Vector4 = new Vector4EqualityComparer(); + public static readonly IEqualityComparer Color = new ColorEqualityComparer(); + public static readonly IEqualityComparer Color32 = new Color32EqualityComparer(); + public static readonly IEqualityComparer Rect = new RectEqualityComparer(); + public static readonly IEqualityComparer Bounds = new BoundsEqualityComparer(); + public static readonly IEqualityComparer Quaternion = new QuaternionEqualityComparer(); + + static readonly RuntimeTypeHandle vector2Type = typeof(Vector2).TypeHandle; + static readonly RuntimeTypeHandle vector3Type = typeof(Vector3).TypeHandle; + static readonly RuntimeTypeHandle vector4Type = typeof(Vector4).TypeHandle; + static readonly RuntimeTypeHandle colorType = typeof(Color).TypeHandle; + static readonly RuntimeTypeHandle color32Type = typeof(Color32).TypeHandle; + static readonly RuntimeTypeHandle rectType = typeof(Rect).TypeHandle; + static readonly RuntimeTypeHandle boundsType = typeof(Bounds).TypeHandle; + static readonly RuntimeTypeHandle quaternionType = typeof(Quaternion).TypeHandle; + +#if UNITY_2017_2_OR_NEWER + + public static readonly IEqualityComparer Vector2Int = new Vector2IntEqualityComparer(); + public static readonly IEqualityComparer Vector3Int = new Vector3IntEqualityComparer(); + public static readonly IEqualityComparer RangeInt = new RangeIntEqualityComparer(); + public static readonly IEqualityComparer RectInt = new RectIntEqualityComparer(); + public static readonly IEqualityComparer BoundsInt = new BoundsIntEqualityComparer(); + + static readonly RuntimeTypeHandle vector2IntType = typeof(Vector2Int).TypeHandle; + static readonly RuntimeTypeHandle vector3IntType = typeof(Vector3Int).TypeHandle; + static readonly RuntimeTypeHandle rangeIntType = typeof(RangeInt).TypeHandle; + static readonly RuntimeTypeHandle rectIntType = typeof(RectInt).TypeHandle; + static readonly RuntimeTypeHandle boundsIntType = typeof(BoundsInt).TypeHandle; + +#endif + + static class Cache + { + public static readonly IEqualityComparer Comparer; + + static Cache() + { + var comparer = GetDefaultHelper(typeof(T)); + if (comparer == null) + { + Comparer = EqualityComparer.Default; + } + else + { + Comparer = (IEqualityComparer)comparer; + } + } + } + + public static IEqualityComparer GetDefault() + { + return Cache.Comparer; + } + + static object GetDefaultHelper(Type type) + { + var t = type.TypeHandle; + + if (t.Equals(vector2Type)) return (object)UnityEqualityComparer.Vector2; + if (t.Equals(vector3Type)) return (object)UnityEqualityComparer.Vector3; + if (t.Equals(vector4Type)) return (object)UnityEqualityComparer.Vector4; + if (t.Equals(colorType)) return (object)UnityEqualityComparer.Color; + if (t.Equals(color32Type)) return (object)UnityEqualityComparer.Color32; + if (t.Equals(rectType)) return (object)UnityEqualityComparer.Rect; + if (t.Equals(boundsType)) return (object)UnityEqualityComparer.Bounds; + if (t.Equals(quaternionType)) return (object)UnityEqualityComparer.Quaternion; + +#if UNITY_2017_2_OR_NEWER + + if (t.Equals(vector2IntType)) return (object)UnityEqualityComparer.Vector2Int; + if (t.Equals(vector3IntType)) return (object)UnityEqualityComparer.Vector3Int; + if (t.Equals(rangeIntType)) return (object)UnityEqualityComparer.RangeInt; + if (t.Equals(rectIntType)) return (object)UnityEqualityComparer.RectInt; + if (t.Equals(boundsIntType)) return (object)UnityEqualityComparer.BoundsInt; +#endif + + return null; + } + + sealed class Vector2EqualityComparer : IEqualityComparer + { + public bool Equals(Vector2 self, Vector2 vector) + { + return self.x.Equals(vector.x) && self.y.Equals(vector.y); + } + + public int GetHashCode(Vector2 obj) + { + return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2; + } + } + + sealed class Vector3EqualityComparer : IEqualityComparer + { + public bool Equals(Vector3 self, Vector3 vector) + { + return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z); + } + + public int GetHashCode(Vector3 obj) + { + return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2; + } + } + + sealed class Vector4EqualityComparer : IEqualityComparer + { + public bool Equals(Vector4 self, Vector4 vector) + { + return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z) && self.w.Equals(vector.w); + } + + public int GetHashCode(Vector4 obj) + { + return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2 ^ obj.w.GetHashCode() >> 1; + } + } + + sealed class ColorEqualityComparer : IEqualityComparer + { + public bool Equals(Color self, Color other) + { + return self.r.Equals(other.r) && self.g.Equals(other.g) && self.b.Equals(other.b) && self.a.Equals(other.a); + } + + public int GetHashCode(Color obj) + { + return obj.r.GetHashCode() ^ obj.g.GetHashCode() << 2 ^ obj.b.GetHashCode() >> 2 ^ obj.a.GetHashCode() >> 1; + } + } + + sealed class RectEqualityComparer : IEqualityComparer + { + public bool Equals(Rect self, Rect other) + { + return self.x.Equals(other.x) && self.width.Equals(other.width) && self.y.Equals(other.y) && self.height.Equals(other.height); + } + + public int GetHashCode(Rect obj) + { + return obj.x.GetHashCode() ^ obj.width.GetHashCode() << 2 ^ obj.y.GetHashCode() >> 2 ^ obj.height.GetHashCode() >> 1; + } + } + + sealed class BoundsEqualityComparer : IEqualityComparer + { + public bool Equals(Bounds self, Bounds vector) + { + return self.center.Equals(vector.center) && self.extents.Equals(vector.extents); + } + + public int GetHashCode(Bounds obj) + { + return obj.center.GetHashCode() ^ obj.extents.GetHashCode() << 2; + } + } + + sealed class QuaternionEqualityComparer : IEqualityComparer + { + public bool Equals(Quaternion self, Quaternion vector) + { + return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z) && self.w.Equals(vector.w); + } + + public int GetHashCode(Quaternion obj) + { + return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2 ^ obj.w.GetHashCode() >> 1; + } + } + + sealed class Color32EqualityComparer : IEqualityComparer + { + public bool Equals(Color32 self, Color32 vector) + { + return self.a.Equals(vector.a) && self.r.Equals(vector.r) && self.g.Equals(vector.g) && self.b.Equals(vector.b); + } + + public int GetHashCode(Color32 obj) + { + return obj.a.GetHashCode() ^ obj.r.GetHashCode() << 2 ^ obj.g.GetHashCode() >> 2 ^ obj.b.GetHashCode() >> 1; + } + } + +#if UNITY_2017_2_OR_NEWER + + sealed class Vector2IntEqualityComparer : IEqualityComparer + { + public bool Equals(Vector2Int self, Vector2Int vector) + { + return self.x.Equals(vector.x) && self.y.Equals(vector.y); + } + + public int GetHashCode(Vector2Int obj) + { + return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2; + } + } + + sealed class Vector3IntEqualityComparer : IEqualityComparer + { + public static readonly Vector3IntEqualityComparer Default = new Vector3IntEqualityComparer(); + + public bool Equals(Vector3Int self, Vector3Int vector) + { + return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z); + } + + public int GetHashCode(Vector3Int obj) + { + return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2; + } + } + + sealed class RangeIntEqualityComparer : IEqualityComparer + { + public bool Equals(RangeInt self, RangeInt vector) + { + return self.start.Equals(vector.start) && self.length.Equals(vector.length); + } + + public int GetHashCode(RangeInt obj) + { + return obj.start.GetHashCode() ^ obj.length.GetHashCode() << 2; + } + } + + sealed class RectIntEqualityComparer : IEqualityComparer + { + public bool Equals(RectInt self, RectInt other) + { + return self.x.Equals(other.x) && self.width.Equals(other.width) && self.y.Equals(other.y) && self.height.Equals(other.height); + } + + public int GetHashCode(RectInt obj) + { + return obj.x.GetHashCode() ^ obj.width.GetHashCode() << 2 ^ obj.y.GetHashCode() >> 2 ^ obj.height.GetHashCode() >> 1; + } + } + + sealed class BoundsIntEqualityComparer : IEqualityComparer + { + public bool Equals(BoundsInt self, BoundsInt vector) + { + return Vector3IntEqualityComparer.Default.Equals(self.position, vector.position) + && Vector3IntEqualityComparer.Default.Equals(self.size, vector.size); + } + + public int GetHashCode(BoundsInt obj) + { + return Vector3IntEqualityComparer.Default.GetHashCode(obj.position) ^ Vector3IntEqualityComparer.Default.GetHashCode(obj.size) << 2; + } + } + +#endif + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs.meta new file mode 100644 index 00000000..79eb04f6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ebaaf14253c9cfb47b23283218ff9b67 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityWebRequestExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityWebRequestExtensions.cs new file mode 100644 index 00000000..0da9f5a7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityWebRequestExtensions.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine.Networking; + +namespace Cysharp.Threading.Tasks.Internal +{ +#if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT) + + internal static class UnityWebRequestResultExtensions + { + public static bool IsError(this UnityWebRequest unityWebRequest) + { +#if UNITY_2020_2_OR_NEWER + var result = unityWebRequest.result; + return (result == UnityWebRequest.Result.ConnectionError) + || (result == UnityWebRequest.Result.DataProcessingError) + || (result == UnityWebRequest.Result.ProtocolError); +#else + return unityWebRequest.isHttpError || unityWebRequest.isNetworkError; +#endif + } + } + +#endif +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityWebRequestExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityWebRequestExtensions.cs.meta new file mode 100644 index 00000000..54bd2eb5 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/UnityWebRequestExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 111ba0e639de1d7428af6c823ead4918 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ValueStopwatch.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ValueStopwatch.cs new file mode 100644 index 00000000..d55d1f6c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ValueStopwatch.cs @@ -0,0 +1,37 @@ +using System; +using System.Diagnostics; + +namespace Cysharp.Threading.Tasks.Internal +{ + internal readonly struct ValueStopwatch + { + static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency; + + readonly long startTimestamp; + + public static ValueStopwatch StartNew() => new ValueStopwatch(Stopwatch.GetTimestamp()); + + ValueStopwatch(long startTimestamp) + { + this.startTimestamp = startTimestamp; + } + + public TimeSpan Elapsed => TimeSpan.FromTicks(this.ElapsedTicks); + + public bool IsInvalid => startTimestamp == 0; + + public long ElapsedTicks + { + get + { + if (startTimestamp == 0) + { + throw new InvalidOperationException("Detected invalid initialization(use 'default'), only to create from StartNew()."); + } + + var delta = Stopwatch.GetTimestamp() - startTimestamp; + return (long)(delta * TimestampToTicks); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ValueStopwatch.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ValueStopwatch.cs.meta new file mode 100644 index 00000000..b7c6b09c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/ValueStopwatch.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f16fb466974ad034c8732c79c7fd67ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs new file mode 100644 index 00000000..3feaad88 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs @@ -0,0 +1,334 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Internal +{ + // Add, Remove, Enumerate with sweep. All operations are thread safe(in spinlock). + internal class WeakDictionary + where TKey : class + { + Entry[] buckets; + int size; + SpinLock gate; // mutable struct(not readonly) + + readonly float loadFactor; + readonly IEqualityComparer keyEqualityComparer; + + public WeakDictionary(int capacity = 4, float loadFactor = 0.75f, IEqualityComparer keyComparer = null) + { + var tableSize = CalculateCapacity(capacity, loadFactor); + this.buckets = new Entry[tableSize]; + this.loadFactor = loadFactor; + this.gate = new SpinLock(false); + this.keyEqualityComparer = keyComparer ?? EqualityComparer.Default; + } + + public bool TryAdd(TKey key, TValue value) + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + return TryAddInternal(key, value); + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + public bool TryGetValue(TKey key, out TValue value) + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + if (TryGetEntry(key, out _, out var entry)) + { + value = entry.Value; + return true; + } + + value = default(TValue); + return false; + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + public bool TryRemove(TKey key) + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + if (TryGetEntry(key, out var hashIndex, out var entry)) + { + Remove(hashIndex, entry); + return true; + } + + return false; + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + bool TryAddInternal(TKey key, TValue value) + { + var nextCapacity = CalculateCapacity(size + 1, loadFactor); + + TRY_ADD_AGAIN: + if (buckets.Length < nextCapacity) + { + // rehash + var nextBucket = new Entry[nextCapacity]; + for (int i = 0; i < buckets.Length; i++) + { + var e = buckets[i]; + while (e != null) + { + AddToBuckets(nextBucket, key, e.Value, e.Hash); + e = e.Next; + } + } + + buckets = nextBucket; + goto TRY_ADD_AGAIN; + } + else + { + // add entry + var successAdd = AddToBuckets(buckets, key, value, keyEqualityComparer.GetHashCode(key)); + if (successAdd) size++; + return successAdd; + } + } + + bool AddToBuckets(Entry[] targetBuckets, TKey newKey, TValue value, int keyHash) + { + var h = keyHash; + var hashIndex = h & (targetBuckets.Length - 1); + + TRY_ADD_AGAIN: + if (targetBuckets[hashIndex] == null) + { + targetBuckets[hashIndex] = new Entry + { + Key = new WeakReference(newKey, false), + Value = value, + Hash = h + }; + + return true; + } + else + { + // add to last. + var entry = targetBuckets[hashIndex]; + while (entry != null) + { + if (entry.Key.TryGetTarget(out var target)) + { + if (keyEqualityComparer.Equals(newKey, target)) + { + return false; // duplicate + } + } + else + { + Remove(hashIndex, entry); + if (targetBuckets[hashIndex] == null) goto TRY_ADD_AGAIN; // add new entry + } + + if (entry.Next != null) + { + entry = entry.Next; + } + else + { + // found last + entry.Next = new Entry + { + Key = new WeakReference(newKey, false), + Value = value, + Hash = h + }; + entry.Next.Prev = entry; + } + } + + return false; + } + } + + bool TryGetEntry(TKey key, out int hashIndex, out Entry entry) + { + var table = buckets; + var hash = keyEqualityComparer.GetHashCode(key); + hashIndex = hash & table.Length - 1; + entry = table[hashIndex]; + + while (entry != null) + { + if (entry.Key.TryGetTarget(out var target)) + { + if (keyEqualityComparer.Equals(key, target)) + { + return true; + } + } + else + { + // sweap + Remove(hashIndex, entry); + } + + entry = entry.Next; + } + + return false; + } + + void Remove(int hashIndex, Entry entry) + { + if (entry.Prev == null && entry.Next == null) + { + buckets[hashIndex] = null; + } + else + { + if (entry.Prev == null) + { + buckets[hashIndex] = entry.Next; + } + if (entry.Prev != null) + { + entry.Prev.Next = entry.Next; + } + if (entry.Next != null) + { + entry.Next.Prev = entry.Prev; + } + } + size--; + } + + public List> ToList() + { + var list = new List>(size); + ToList(ref list, false); + return list; + } + + // avoid allocate everytime. + public int ToList(ref List> list, bool clear = true) + { + if (clear) + { + list.Clear(); + } + + var listIndex = 0; + + bool lockTaken = false; + try + { + for (int i = 0; i < buckets.Length; i++) + { + var entry = buckets[i]; + while (entry != null) + { + if (entry.Key.TryGetTarget(out var target)) + { + var item = new KeyValuePair(target, entry.Value); + if (listIndex < list.Count) + { + list[listIndex++] = item; + } + else + { + list.Add(item); + listIndex++; + } + } + else + { + // sweap + Remove(i, entry); + } + + entry = entry.Next; + } + } + } + finally + { + if (lockTaken) gate.Exit(false); + } + + return listIndex; + } + + static int CalculateCapacity(int collectionSize, float loadFactor) + { + var size = (int)(((float)collectionSize) / loadFactor); + + size--; + size |= size >> 1; + size |= size >> 2; + size |= size >> 4; + size |= size >> 8; + size |= size >> 16; + size += 1; + + if (size < 8) + { + size = 8; + } + return size; + } + + class Entry + { + public WeakReference Key; + public TValue Value; + public int Hash; + public Entry Prev; + public Entry Next; + + // debug only + public override string ToString() + { + if (Key.TryGetTarget(out var target)) + { + return target + "(" + Count() + ")"; + } + else + { + return "(Dead)"; + } + } + + int Count() + { + var count = 1; + var n = this; + while (n.Next != null) + { + count++; + n = n.Next; + } + return count; + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs.meta new file mode 100644 index 00000000..9dc1672a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Internal/WeakDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c78563864409714593226af59bcb6f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq.meta new file mode 100644 index 00000000..e5b1643e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 99f78347d38e1e449950f6461f034425 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Aggregate.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Aggregate.cs new file mode 100644 index 00000000..78647ff3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Aggregate.cs @@ -0,0 +1,318 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AggregateAsync(this IUniTaskAsyncEnumerable source, Func accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.AggregateAsync(source, accumulator, cancellationToken); + } + + public static UniTask AggregateAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.AggregateAsync(source, seed, accumulator, cancellationToken); + } + + public static UniTask AggregateAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, Func resultSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + Error.ThrowArgumentNullException(accumulator, nameof(resultSelector)); + + return Aggregate.AggregateAsync(source, seed, accumulator, resultSelector, cancellationToken); + } + + public static UniTask AggregateAwaitAsync(this IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.AggregateAwaitAsync(source, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.AggregateAwaitAsync(source, seed, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + Error.ThrowArgumentNullException(accumulator, nameof(resultSelector)); + + return Aggregate.AggregateAwaitAsync(source, seed, accumulator, resultSelector, cancellationToken); + } + + public static UniTask AggregateAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.AggregateAwaitWithCancellationAsync(source, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.AggregateAwaitWithCancellationAsync(source, seed, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + Error.ThrowArgumentNullException(accumulator, nameof(resultSelector)); + + return Aggregate.AggregateAwaitWithCancellationAsync(source, seed, accumulator, resultSelector, cancellationToken); + } + } + + internal static class Aggregate + { + internal static async UniTask AggregateAsync(IUniTaskAsyncEnumerable source, Func accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + throw Error.NoElements(); + } + + while (await e.MoveNextAsync()) + { + value = accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AggregateAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AggregateAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, Func resultSelector, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = accumulator(value, e.Current); + } + return resultSelector(value); + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // with async + + internal static async UniTask AggregateAwaitAsync(IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + throw Error.NoElements(); + } + + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AggregateAwaitAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AggregateAwaitAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current); + } + return await resultSelector(value); + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + + // with cancellation + + internal static async UniTask AggregateAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + throw Error.NoElements(); + } + + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current, cancellationToken); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AggregateAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current, cancellationToken); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AggregateAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current, cancellationToken); + } + return await resultSelector(value, cancellationToken); + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Aggregate.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Aggregate.cs.meta new file mode 100644 index 00000000..837df4a9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Aggregate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5dc68c05a4228c643937f6ebd185bcca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/All.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/All.cs new file mode 100644 index 00000000..5d6d5f0e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/All.cs @@ -0,0 +1,108 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AllAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return All.AllAsync(source, predicate, cancellationToken); + } + + public static UniTask AllAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return All.AllAwaitAsync(source, predicate, cancellationToken); + } + + public static UniTask AllAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return All.AllAwaitWithCancellationAsync(source, predicate, cancellationToken); + } + } + + internal static class All + { + internal static async UniTask AllAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (!predicate(e.Current)) + { + return false; + } + } + + return true; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AllAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (!await predicate(e.Current)) + { + return false; + } + } + + return true; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AllAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (!await predicate(e.Current, cancellationToken)) + { + return false; + } + } + + return true; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/All.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/All.cs.meta new file mode 100644 index 00000000..d378ff0e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/All.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7271437e0033af2448b600ee248924dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Any.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Any.cs new file mode 100644 index 00000000..2d43167c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Any.cs @@ -0,0 +1,136 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AnyAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Any.AnyAsync(source, cancellationToken); + } + + public static UniTask AnyAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Any.AnyAsync(source, predicate, cancellationToken); + } + + public static UniTask AnyAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Any.AnyAwaitAsync(source, predicate, cancellationToken); + } + + public static UniTask AnyAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Any.AnyAwaitWithCancellationAsync(source, predicate, cancellationToken); + } + } + + internal static class Any + { + internal static async UniTask AnyAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + if (await e.MoveNextAsync()) + { + return true; + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AnyAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (predicate(e.Current)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AnyAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask AnyAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current, cancellationToken)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Any.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Any.cs.meta new file mode 100644 index 00000000..1070bcc8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Any.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2b2e65745263994fbe34f3e0ec8eb12 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AppendPrepend.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AppendPrepend.cs new file mode 100644 index 00000000..3935afd8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AppendPrepend.cs @@ -0,0 +1,151 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Append(this IUniTaskAsyncEnumerable source, TSource element) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new AppendPrepend(source, element, true); + } + + public static IUniTaskAsyncEnumerable Prepend(this IUniTaskAsyncEnumerable source, TSource element) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new AppendPrepend(source, element, false); + } + } + + internal sealed class AppendPrepend : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly TSource element; + readonly bool append; // or prepend + + public AppendPrepend(IUniTaskAsyncEnumerable source, TSource element, bool append) + { + this.source = source; + this.element = element; + this.append = append; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _AppendPrepend(source, element, append, cancellationToken); + } + + sealed class _AppendPrepend : MoveNextSource, IUniTaskAsyncEnumerator + { + enum State : byte + { + None, + RequirePrepend, + RequireAppend, + Completed + } + + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly TSource element; + CancellationToken cancellationToken; + + State state; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public _AppendPrepend(IUniTaskAsyncEnumerable source, TSource element, bool append, CancellationToken cancellationToken) + { + this.source = source; + this.element = element; + this.state = append ? State.RequireAppend : State.RequirePrepend; + this.cancellationToken = cancellationToken; + + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (enumerator == null) + { + if (state == State.RequirePrepend) + { + Current = element; + state = State.None; + return CompletedTasks.True; + } + + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + if (state == State.Completed) + { + return CompletedTasks.False; + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + + if (awaiter.IsCompleted) + { + MoveNextCoreDelegate(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void MoveNextCore(object state) + { + var self = (_AppendPrepend)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + if (self.state == State.RequireAppend) + { + self.state = State.Completed; + self.Current = self.element; + self.completionSource.TrySetResult(true); + } + else + { + self.state = State.Completed; + self.completionSource.TrySetResult(false); + } + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AppendPrepend.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AppendPrepend.cs.meta new file mode 100644 index 00000000..6d2ee046 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AppendPrepend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3268ec424b8055f45aa2a26d17c80468 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsUniTaskAsyncEnumerable.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsUniTaskAsyncEnumerable.cs new file mode 100644 index 00000000..c00452e1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsUniTaskAsyncEnumerable.cs @@ -0,0 +1,10 @@ +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable AsUniTaskAsyncEnumerable(this IUniTaskAsyncEnumerable source) + { + return source; + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsUniTaskAsyncEnumerable.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsUniTaskAsyncEnumerable.cs.meta new file mode 100644 index 00000000..90f6207c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsUniTaskAsyncEnumerable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69866e262589ea643bbc62a1d696077a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsyncEnumeratorBase.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsyncEnumeratorBase.cs new file mode 100644 index 00000000..e7f99685 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsyncEnumeratorBase.cs @@ -0,0 +1,356 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + // note: refactor all inherit class and should remove this. + // see Select and Where. + internal abstract class AsyncEnumeratorBase : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action moveNextCallbackDelegate = MoveNextCallBack; + + readonly IUniTaskAsyncEnumerable source; + protected CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter sourceMoveNext; + + public AsyncEnumeratorBase(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 4); + } + + // abstract + + /// + /// If return value is false, continue source.MoveNext. + /// + protected abstract bool TryMoveNextCore(bool sourceHasCurrent, out bool result); + + // Util + protected TSource SourceCurrent => enumerator.Current; + + // IUniTaskAsyncEnumerator + + public TResult Current { get; protected set; } + + public UniTask MoveNextAsync() + { + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + if (!OnFirstIteration()) + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + protected virtual bool OnFirstIteration() + { + return false; + } + + protected void SourceMoveNext() + { + CONTINUE: + sourceMoveNext = enumerator.MoveNextAsync().GetAwaiter(); + if (sourceMoveNext.IsCompleted) + { + bool result = false; + try + { + if (!TryMoveNextCore(sourceMoveNext.GetResult(), out result)) + { + goto CONTINUE; + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + } + else + { + completionSource.TrySetResult(result); + } + } + else + { + sourceMoveNext.SourceOnCompleted(moveNextCallbackDelegate, this); + } + } + + static void MoveNextCallBack(object state) + { + var self = (AsyncEnumeratorBase)state; + bool result; + try + { + if (!self.TryMoveNextCore(self.sourceMoveNext.GetResult(), out result)) + { + self.SourceMoveNext(); + return; + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(result); + } + } + + // if require additional resource to dispose, override and call base.DisposeAsync. + public virtual UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + + internal abstract class AsyncEnumeratorAwaitSelectorBase : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action moveNextCallbackDelegate = MoveNextCallBack; + static readonly Action setCurrentCallbackDelegate = SetCurrentCallBack; + + + readonly IUniTaskAsyncEnumerable source; + protected CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter sourceMoveNext; + + UniTask.Awaiter resultAwaiter; + + public AsyncEnumeratorAwaitSelectorBase(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 4); + } + + // abstract + + protected abstract UniTask TransformAsync(TSource sourceCurrent); + protected abstract bool TrySetCurrentCore(TAwait awaitResult, out bool terminateIteration); + + // Util + protected TSource SourceCurrent { get; private set; } + + protected (bool waitCallback, bool requireNextIteration) ActionCompleted(bool trySetCurrentResult, out bool moveNextResult) + { + if (trySetCurrentResult) + { + moveNextResult = true; + return (false, false); + } + else + { + moveNextResult = default; + return (false, true); + } + } + protected (bool waitCallback, bool requireNextIteration) WaitAwaitCallback(out bool moveNextResult) { moveNextResult = default; return (true, false); } + protected (bool waitCallback, bool requireNextIteration) IterateFinished(out bool moveNextResult) { moveNextResult = false; return (false, false); } + + // IUniTaskAsyncEnumerator + + public TResult Current { get; protected set; } + + public UniTask MoveNextAsync() + { + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + protected void SourceMoveNext() + { + CONTINUE: + sourceMoveNext = enumerator.MoveNextAsync().GetAwaiter(); + if (sourceMoveNext.IsCompleted) + { + bool result = false; + try + { + (bool waitCallback, bool requireNextIteration) = TryMoveNextCore(sourceMoveNext.GetResult(), out result); + + if (waitCallback) + { + return; + } + + if (requireNextIteration) + { + goto CONTINUE; + } + else + { + completionSource.TrySetResult(result); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + else + { + sourceMoveNext.SourceOnCompleted(moveNextCallbackDelegate, this); + } + } + + (bool waitCallback, bool requireNextIteration) TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + SourceCurrent = enumerator.Current; + var task = TransformAsync(SourceCurrent); + if (UnwarapTask(task, out var taskResult)) + { + var currentResult = TrySetCurrentCore(taskResult, out var terminateIteration); + if (terminateIteration) + { + return IterateFinished(out result); + } + + return ActionCompleted(currentResult, out result); + } + else + { + return WaitAwaitCallback(out result); + } + } + + return IterateFinished(out result); + } + + protected bool UnwarapTask(UniTask taskResult, out TAwait result) + { + resultAwaiter = taskResult.GetAwaiter(); + + if (resultAwaiter.IsCompleted) + { + result = resultAwaiter.GetResult(); + return true; + } + else + { + resultAwaiter.SourceOnCompleted(setCurrentCallbackDelegate, this); + result = default; + return false; + } + } + + static void MoveNextCallBack(object state) + { + var self = (AsyncEnumeratorAwaitSelectorBase)state; + bool result = false; + try + { + (bool waitCallback, bool requireNextIteration) = self.TryMoveNextCore(self.sourceMoveNext.GetResult(), out result); + + if (waitCallback) + { + return; + } + + if (requireNextIteration) + { + self.SourceMoveNext(); + return; + } + else + { + self.completionSource.TrySetResult(result); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + + static void SetCurrentCallBack(object state) + { + var self = (AsyncEnumeratorAwaitSelectorBase)state; + + bool doneSetCurrent; + bool terminateIteration; + try + { + var result = self.resultAwaiter.GetResult(); + doneSetCurrent = self.TrySetCurrentCore(result, out terminateIteration); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + if (doneSetCurrent) + { + self.completionSource.TrySetResult(true); + } + else + { + if (terminateIteration) + { + self.completionSource.TrySetResult(false); + } + else + { + self.SourceMoveNext(); + } + } + } + } + + // if require additional resource to dispose, override and call base.DisposeAsync. + public virtual UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsyncEnumeratorBase.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsyncEnumeratorBase.cs.meta new file mode 100644 index 00000000..a4e96dc0 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/AsyncEnumeratorBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 01ba1d3b17e13fb4c95740131c7e6e19 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Average.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Average.cs new file mode 100644 index 00000000..b2ce42c1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Average.cs @@ -0,0 +1,1524 @@ +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.AverageAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.AverageAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + } + + internal static class Average + { + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask AverageAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Average.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Average.cs.meta new file mode 100644 index 00000000..8f60dfc5 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Average.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58499f95012fb3c47bb7bcbc5862e562 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Buffer.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Buffer.cs new file mode 100644 index 00000000..be395b68 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Buffer.cs @@ -0,0 +1,345 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable> Buffer(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + if (count <= 0) throw Error.ArgumentOutOfRange(nameof(count)); + + return new Buffer(source, count); + } + + public static IUniTaskAsyncEnumerable> Buffer(this IUniTaskAsyncEnumerable source, Int32 count, Int32 skip) + { + Error.ThrowArgumentNullException(source, nameof(source)); + if (count <= 0) throw Error.ArgumentOutOfRange(nameof(count)); + if (skip <= 0) throw Error.ArgumentOutOfRange(nameof(skip)); + + return new BufferSkip(source, count, skip); + } + } + + internal sealed class Buffer : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public Buffer(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Buffer(source, count, cancellationToken); + } + + sealed class _Buffer : MoveNextSource, IUniTaskAsyncEnumerator> + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + bool continueNext; + + bool completed; + List buffer; + + public _Buffer(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + + TaskTracker.TrackActiveTask(this, 3); + } + + public IList Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + buffer = new List(count); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + if (completed) + { + if (buffer != null && buffer.Count > 0) + { + var ret = buffer; + buffer = null; + Current = ret; + completionSource.TrySetResult(true); + return; + } + else + { + completionSource.TrySetResult(false); + return; + } + } + + try + { + + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (_Buffer)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.buffer.Add(self.enumerator.Current); + + if (self.buffer.Count == self.count) + { + self.Current = self.buffer; + self.buffer = new List(self.count); + self.continueNext = false; + self.completionSource.TrySetResult(true); + return; + } + else + { + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.completed = true; + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + + internal sealed class BufferSkip : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + readonly int skip; + + public BufferSkip(IUniTaskAsyncEnumerable source, int count, int skip) + { + this.source = source; + this.count = count; + this.skip = skip; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _BufferSkip(source, count, skip, cancellationToken); + } + + sealed class _BufferSkip : MoveNextSource, IUniTaskAsyncEnumerator> + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + readonly int skip; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + bool continueNext; + + bool completed; + Queue> buffers; + int index = 0; + + public _BufferSkip(IUniTaskAsyncEnumerable source, int count, int skip, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.skip = skip; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public IList Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + buffers = new Queue>(); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + if (completed) + { + if (buffers.Count > 0) + { + Current = buffers.Dequeue(); + completionSource.TrySetResult(true); + return; + } + else + { + completionSource.TrySetResult(false); + return; + } + } + + try + { + + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (_BufferSkip)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.index++ % self.skip == 0) + { + self.buffers.Enqueue(new List(self.count)); + } + + var item = self.enumerator.Current; + foreach (var buffer in self.buffers) + { + buffer.Add(item); + } + + if (self.buffers.Count > 0 && self.buffers.Peek().Count == self.count) + { + self.Current = self.buffers.Dequeue(); + self.continueNext = false; + self.completionSource.TrySetResult(true); + return; + } + else + { + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.completed = true; + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Buffer.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Buffer.cs.meta new file mode 100644 index 00000000..e7154e4d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Buffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 951310243334a3148a7872977cb31c5c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Cast.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Cast.cs new file mode 100644 index 00000000..0a0c0f8f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Cast.cs @@ -0,0 +1,53 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Cast(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Cast(source); + } + } + + internal sealed class Cast : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public Cast(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Cast(source, cancellationToken); + } + + class _Cast : AsyncEnumeratorBase + { + public _Cast(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + Current = (TResult)SourceCurrent; + result = true; + return true; + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Cast.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Cast.cs.meta new file mode 100644 index 00000000..913b043c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Cast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edebeae8b61352b428abe9ce8f3fc71a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/CombineLatest.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/CombineLatest.cs new file mode 100644 index 00000000..92fb1daa --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/CombineLatest.cs @@ -0,0 +1,11372 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(source10, nameof(source10)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(source10, nameof(source10)); + Error.ThrowArgumentNullException(source11, nameof(source11)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(source10, nameof(source10)); + Error.ThrowArgumentNullException(source11, nameof(source11)); + Error.ThrowArgumentNullException(source12, nameof(source12)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(source10, nameof(source10)); + Error.ThrowArgumentNullException(source11, nameof(source11)); + Error.ThrowArgumentNullException(source12, nameof(source12)); + Error.ThrowArgumentNullException(source13, nameof(source13)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, IUniTaskAsyncEnumerable source14, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(source10, nameof(source10)); + Error.ThrowArgumentNullException(source11, nameof(source11)); + Error.ThrowArgumentNullException(source12, nameof(source12)); + Error.ThrowArgumentNullException(source13, nameof(source13)); + Error.ThrowArgumentNullException(source14, nameof(source14)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, source14, resultSelector); + } + + public static IUniTaskAsyncEnumerable CombineLatest(this IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, IUniTaskAsyncEnumerable source14, IUniTaskAsyncEnumerable source15, Func resultSelector) + { + Error.ThrowArgumentNullException(source1, nameof(source1)); + Error.ThrowArgumentNullException(source2, nameof(source2)); + Error.ThrowArgumentNullException(source3, nameof(source3)); + Error.ThrowArgumentNullException(source4, nameof(source4)); + Error.ThrowArgumentNullException(source5, nameof(source5)); + Error.ThrowArgumentNullException(source6, nameof(source6)); + Error.ThrowArgumentNullException(source7, nameof(source7)); + Error.ThrowArgumentNullException(source8, nameof(source8)); + Error.ThrowArgumentNullException(source9, nameof(source9)); + Error.ThrowArgumentNullException(source10, nameof(source10)); + Error.ThrowArgumentNullException(source11, nameof(source11)); + Error.ThrowArgumentNullException(source12, nameof(source12)); + Error.ThrowArgumentNullException(source13, nameof(source13)); + Error.ThrowArgumentNullException(source14, nameof(source14)); + Error.ThrowArgumentNullException(source15, nameof(source15)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, source14, source15, resultSelector); + } + + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + const int CompleteCount = 2; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + + if (!running1 || !running2) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2) + { + result = resultSelector(current1, current2); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + const int CompleteCount = 3; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + + if (!running1 || !running2 || !running3) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3) + { + result = resultSelector(current1, current2, current3); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + const int CompleteCount = 4; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4) + { + result = resultSelector(current1, current2, current3, current4); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + const int CompleteCount = 5; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5) + { + result = resultSelector(current1, current2, current3, current4, current5); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + const int CompleteCount = 6; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6) + { + result = resultSelector(current1, current2, current3, current4, current5, current6); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + const int CompleteCount = 7; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + const int CompleteCount = 8; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + const int CompleteCount = 9; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + static readonly Action Completed10Delegate = Completed10; + const int CompleteCount = 10; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + IUniTaskAsyncEnumerator enumerator10; + UniTask.Awaiter awaiter10; + bool hasCurrent10; + bool running10; + T10 current10; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + enumerator10 = source10.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + if (!running10) + { + running10 = true; + awaiter10 = enumerator10.MoveNextAsync().GetAwaiter(); + if (awaiter10.IsCompleted) + { + Completed10(this); + } + else + { + awaiter10.SourceOnCompleted(Completed10Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9 || !running10) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed10(object state) + { + var self = (_CombineLatest)state; + self.running10 = false; + + try + { + if (self.awaiter10.GetResult()) + { + self.hasCurrent10 = true; + self.current10 = self.enumerator10.Current; + goto SUCCESS; + } + else + { + self.running10 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running10 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running10 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter10 = self.enumerator10.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter10.SourceOnCompleted(Completed10Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9 && hasCurrent10) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9, current10); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + if (enumerator10 != null) + { + await enumerator10.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + static readonly Action Completed10Delegate = Completed10; + static readonly Action Completed11Delegate = Completed11; + const int CompleteCount = 11; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + IUniTaskAsyncEnumerator enumerator10; + UniTask.Awaiter awaiter10; + bool hasCurrent10; + bool running10; + T10 current10; + + IUniTaskAsyncEnumerator enumerator11; + UniTask.Awaiter awaiter11; + bool hasCurrent11; + bool running11; + T11 current11; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + enumerator10 = source10.GetAsyncEnumerator(cancellationToken); + enumerator11 = source11.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + if (!running10) + { + running10 = true; + awaiter10 = enumerator10.MoveNextAsync().GetAwaiter(); + if (awaiter10.IsCompleted) + { + Completed10(this); + } + else + { + awaiter10.SourceOnCompleted(Completed10Delegate, this); + } + } + if (!running11) + { + running11 = true; + awaiter11 = enumerator11.MoveNextAsync().GetAwaiter(); + if (awaiter11.IsCompleted) + { + Completed11(this); + } + else + { + awaiter11.SourceOnCompleted(Completed11Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9 || !running10 || !running11) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed10(object state) + { + var self = (_CombineLatest)state; + self.running10 = false; + + try + { + if (self.awaiter10.GetResult()) + { + self.hasCurrent10 = true; + self.current10 = self.enumerator10.Current; + goto SUCCESS; + } + else + { + self.running10 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running10 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running10 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter10 = self.enumerator10.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter10.SourceOnCompleted(Completed10Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed11(object state) + { + var self = (_CombineLatest)state; + self.running11 = false; + + try + { + if (self.awaiter11.GetResult()) + { + self.hasCurrent11 = true; + self.current11 = self.enumerator11.Current; + goto SUCCESS; + } + else + { + self.running11 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running11 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running11 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter11 = self.enumerator11.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter11.SourceOnCompleted(Completed11Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9 && hasCurrent10 && hasCurrent11) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9, current10, current11); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + if (enumerator10 != null) + { + await enumerator10.DisposeAsync(); + } + if (enumerator11 != null) + { + await enumerator11.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + static readonly Action Completed10Delegate = Completed10; + static readonly Action Completed11Delegate = Completed11; + static readonly Action Completed12Delegate = Completed12; + const int CompleteCount = 12; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + IUniTaskAsyncEnumerator enumerator10; + UniTask.Awaiter awaiter10; + bool hasCurrent10; + bool running10; + T10 current10; + + IUniTaskAsyncEnumerator enumerator11; + UniTask.Awaiter awaiter11; + bool hasCurrent11; + bool running11; + T11 current11; + + IUniTaskAsyncEnumerator enumerator12; + UniTask.Awaiter awaiter12; + bool hasCurrent12; + bool running12; + T12 current12; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + enumerator10 = source10.GetAsyncEnumerator(cancellationToken); + enumerator11 = source11.GetAsyncEnumerator(cancellationToken); + enumerator12 = source12.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + if (!running10) + { + running10 = true; + awaiter10 = enumerator10.MoveNextAsync().GetAwaiter(); + if (awaiter10.IsCompleted) + { + Completed10(this); + } + else + { + awaiter10.SourceOnCompleted(Completed10Delegate, this); + } + } + if (!running11) + { + running11 = true; + awaiter11 = enumerator11.MoveNextAsync().GetAwaiter(); + if (awaiter11.IsCompleted) + { + Completed11(this); + } + else + { + awaiter11.SourceOnCompleted(Completed11Delegate, this); + } + } + if (!running12) + { + running12 = true; + awaiter12 = enumerator12.MoveNextAsync().GetAwaiter(); + if (awaiter12.IsCompleted) + { + Completed12(this); + } + else + { + awaiter12.SourceOnCompleted(Completed12Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9 || !running10 || !running11 || !running12) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed10(object state) + { + var self = (_CombineLatest)state; + self.running10 = false; + + try + { + if (self.awaiter10.GetResult()) + { + self.hasCurrent10 = true; + self.current10 = self.enumerator10.Current; + goto SUCCESS; + } + else + { + self.running10 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running10 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running10 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter10 = self.enumerator10.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter10.SourceOnCompleted(Completed10Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed11(object state) + { + var self = (_CombineLatest)state; + self.running11 = false; + + try + { + if (self.awaiter11.GetResult()) + { + self.hasCurrent11 = true; + self.current11 = self.enumerator11.Current; + goto SUCCESS; + } + else + { + self.running11 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running11 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running11 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter11 = self.enumerator11.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter11.SourceOnCompleted(Completed11Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed12(object state) + { + var self = (_CombineLatest)state; + self.running12 = false; + + try + { + if (self.awaiter12.GetResult()) + { + self.hasCurrent12 = true; + self.current12 = self.enumerator12.Current; + goto SUCCESS; + } + else + { + self.running12 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running12 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running12 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter12 = self.enumerator12.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter12.SourceOnCompleted(Completed12Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9 && hasCurrent10 && hasCurrent11 && hasCurrent12) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9, current10, current11, current12); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + if (enumerator10 != null) + { + await enumerator10.DisposeAsync(); + } + if (enumerator11 != null) + { + await enumerator11.DisposeAsync(); + } + if (enumerator12 != null) + { + await enumerator12.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + readonly IUniTaskAsyncEnumerable source13; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + this.source13 = source13; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + static readonly Action Completed10Delegate = Completed10; + static readonly Action Completed11Delegate = Completed11; + static readonly Action Completed12Delegate = Completed12; + static readonly Action Completed13Delegate = Completed13; + const int CompleteCount = 13; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + readonly IUniTaskAsyncEnumerable source13; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + IUniTaskAsyncEnumerator enumerator10; + UniTask.Awaiter awaiter10; + bool hasCurrent10; + bool running10; + T10 current10; + + IUniTaskAsyncEnumerator enumerator11; + UniTask.Awaiter awaiter11; + bool hasCurrent11; + bool running11; + T11 current11; + + IUniTaskAsyncEnumerator enumerator12; + UniTask.Awaiter awaiter12; + bool hasCurrent12; + bool running12; + T12 current12; + + IUniTaskAsyncEnumerator enumerator13; + UniTask.Awaiter awaiter13; + bool hasCurrent13; + bool running13; + T13 current13; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + this.source13 = source13; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + enumerator10 = source10.GetAsyncEnumerator(cancellationToken); + enumerator11 = source11.GetAsyncEnumerator(cancellationToken); + enumerator12 = source12.GetAsyncEnumerator(cancellationToken); + enumerator13 = source13.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + if (!running10) + { + running10 = true; + awaiter10 = enumerator10.MoveNextAsync().GetAwaiter(); + if (awaiter10.IsCompleted) + { + Completed10(this); + } + else + { + awaiter10.SourceOnCompleted(Completed10Delegate, this); + } + } + if (!running11) + { + running11 = true; + awaiter11 = enumerator11.MoveNextAsync().GetAwaiter(); + if (awaiter11.IsCompleted) + { + Completed11(this); + } + else + { + awaiter11.SourceOnCompleted(Completed11Delegate, this); + } + } + if (!running12) + { + running12 = true; + awaiter12 = enumerator12.MoveNextAsync().GetAwaiter(); + if (awaiter12.IsCompleted) + { + Completed12(this); + } + else + { + awaiter12.SourceOnCompleted(Completed12Delegate, this); + } + } + if (!running13) + { + running13 = true; + awaiter13 = enumerator13.MoveNextAsync().GetAwaiter(); + if (awaiter13.IsCompleted) + { + Completed13(this); + } + else + { + awaiter13.SourceOnCompleted(Completed13Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9 || !running10 || !running11 || !running12 || !running13) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed10(object state) + { + var self = (_CombineLatest)state; + self.running10 = false; + + try + { + if (self.awaiter10.GetResult()) + { + self.hasCurrent10 = true; + self.current10 = self.enumerator10.Current; + goto SUCCESS; + } + else + { + self.running10 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running10 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running10 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter10 = self.enumerator10.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter10.SourceOnCompleted(Completed10Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed11(object state) + { + var self = (_CombineLatest)state; + self.running11 = false; + + try + { + if (self.awaiter11.GetResult()) + { + self.hasCurrent11 = true; + self.current11 = self.enumerator11.Current; + goto SUCCESS; + } + else + { + self.running11 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running11 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running11 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter11 = self.enumerator11.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter11.SourceOnCompleted(Completed11Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed12(object state) + { + var self = (_CombineLatest)state; + self.running12 = false; + + try + { + if (self.awaiter12.GetResult()) + { + self.hasCurrent12 = true; + self.current12 = self.enumerator12.Current; + goto SUCCESS; + } + else + { + self.running12 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running12 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running12 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter12 = self.enumerator12.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter12.SourceOnCompleted(Completed12Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed13(object state) + { + var self = (_CombineLatest)state; + self.running13 = false; + + try + { + if (self.awaiter13.GetResult()) + { + self.hasCurrent13 = true; + self.current13 = self.enumerator13.Current; + goto SUCCESS; + } + else + { + self.running13 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running13 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running13 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter13 = self.enumerator13.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter13.SourceOnCompleted(Completed13Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9 && hasCurrent10 && hasCurrent11 && hasCurrent12 && hasCurrent13) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9, current10, current11, current12, current13); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + if (enumerator10 != null) + { + await enumerator10.DisposeAsync(); + } + if (enumerator11 != null) + { + await enumerator11.DisposeAsync(); + } + if (enumerator12 != null) + { + await enumerator12.DisposeAsync(); + } + if (enumerator13 != null) + { + await enumerator13.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + readonly IUniTaskAsyncEnumerable source13; + readonly IUniTaskAsyncEnumerable source14; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, IUniTaskAsyncEnumerable source14, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + this.source13 = source13; + this.source14 = source14; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, source14, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + static readonly Action Completed10Delegate = Completed10; + static readonly Action Completed11Delegate = Completed11; + static readonly Action Completed12Delegate = Completed12; + static readonly Action Completed13Delegate = Completed13; + static readonly Action Completed14Delegate = Completed14; + const int CompleteCount = 14; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + readonly IUniTaskAsyncEnumerable source13; + readonly IUniTaskAsyncEnumerable source14; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + IUniTaskAsyncEnumerator enumerator10; + UniTask.Awaiter awaiter10; + bool hasCurrent10; + bool running10; + T10 current10; + + IUniTaskAsyncEnumerator enumerator11; + UniTask.Awaiter awaiter11; + bool hasCurrent11; + bool running11; + T11 current11; + + IUniTaskAsyncEnumerator enumerator12; + UniTask.Awaiter awaiter12; + bool hasCurrent12; + bool running12; + T12 current12; + + IUniTaskAsyncEnumerator enumerator13; + UniTask.Awaiter awaiter13; + bool hasCurrent13; + bool running13; + T13 current13; + + IUniTaskAsyncEnumerator enumerator14; + UniTask.Awaiter awaiter14; + bool hasCurrent14; + bool running14; + T14 current14; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, IUniTaskAsyncEnumerable source14, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + this.source13 = source13; + this.source14 = source14; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + enumerator10 = source10.GetAsyncEnumerator(cancellationToken); + enumerator11 = source11.GetAsyncEnumerator(cancellationToken); + enumerator12 = source12.GetAsyncEnumerator(cancellationToken); + enumerator13 = source13.GetAsyncEnumerator(cancellationToken); + enumerator14 = source14.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + if (!running10) + { + running10 = true; + awaiter10 = enumerator10.MoveNextAsync().GetAwaiter(); + if (awaiter10.IsCompleted) + { + Completed10(this); + } + else + { + awaiter10.SourceOnCompleted(Completed10Delegate, this); + } + } + if (!running11) + { + running11 = true; + awaiter11 = enumerator11.MoveNextAsync().GetAwaiter(); + if (awaiter11.IsCompleted) + { + Completed11(this); + } + else + { + awaiter11.SourceOnCompleted(Completed11Delegate, this); + } + } + if (!running12) + { + running12 = true; + awaiter12 = enumerator12.MoveNextAsync().GetAwaiter(); + if (awaiter12.IsCompleted) + { + Completed12(this); + } + else + { + awaiter12.SourceOnCompleted(Completed12Delegate, this); + } + } + if (!running13) + { + running13 = true; + awaiter13 = enumerator13.MoveNextAsync().GetAwaiter(); + if (awaiter13.IsCompleted) + { + Completed13(this); + } + else + { + awaiter13.SourceOnCompleted(Completed13Delegate, this); + } + } + if (!running14) + { + running14 = true; + awaiter14 = enumerator14.MoveNextAsync().GetAwaiter(); + if (awaiter14.IsCompleted) + { + Completed14(this); + } + else + { + awaiter14.SourceOnCompleted(Completed14Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9 || !running10 || !running11 || !running12 || !running13 || !running14) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed10(object state) + { + var self = (_CombineLatest)state; + self.running10 = false; + + try + { + if (self.awaiter10.GetResult()) + { + self.hasCurrent10 = true; + self.current10 = self.enumerator10.Current; + goto SUCCESS; + } + else + { + self.running10 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running10 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running10 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter10 = self.enumerator10.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter10.SourceOnCompleted(Completed10Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed11(object state) + { + var self = (_CombineLatest)state; + self.running11 = false; + + try + { + if (self.awaiter11.GetResult()) + { + self.hasCurrent11 = true; + self.current11 = self.enumerator11.Current; + goto SUCCESS; + } + else + { + self.running11 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running11 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running11 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter11 = self.enumerator11.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter11.SourceOnCompleted(Completed11Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed12(object state) + { + var self = (_CombineLatest)state; + self.running12 = false; + + try + { + if (self.awaiter12.GetResult()) + { + self.hasCurrent12 = true; + self.current12 = self.enumerator12.Current; + goto SUCCESS; + } + else + { + self.running12 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running12 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running12 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter12 = self.enumerator12.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter12.SourceOnCompleted(Completed12Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed13(object state) + { + var self = (_CombineLatest)state; + self.running13 = false; + + try + { + if (self.awaiter13.GetResult()) + { + self.hasCurrent13 = true; + self.current13 = self.enumerator13.Current; + goto SUCCESS; + } + else + { + self.running13 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running13 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running13 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter13 = self.enumerator13.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter13.SourceOnCompleted(Completed13Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed14(object state) + { + var self = (_CombineLatest)state; + self.running14 = false; + + try + { + if (self.awaiter14.GetResult()) + { + self.hasCurrent14 = true; + self.current14 = self.enumerator14.Current; + goto SUCCESS; + } + else + { + self.running14 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running14 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running14 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter14 = self.enumerator14.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter14.SourceOnCompleted(Completed14Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9 && hasCurrent10 && hasCurrent11 && hasCurrent12 && hasCurrent13 && hasCurrent14) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9, current10, current11, current12, current13, current14); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + if (enumerator10 != null) + { + await enumerator10.DisposeAsync(); + } + if (enumerator11 != null) + { + await enumerator11.DisposeAsync(); + } + if (enumerator12 != null) + { + await enumerator12.DisposeAsync(); + } + if (enumerator13 != null) + { + await enumerator13.DisposeAsync(); + } + if (enumerator14 != null) + { + await enumerator14.DisposeAsync(); + } + } + } + } + + internal class CombineLatest : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + readonly IUniTaskAsyncEnumerable source13; + readonly IUniTaskAsyncEnumerable source14; + readonly IUniTaskAsyncEnumerable source15; + + readonly Func resultSelector; + + public CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, IUniTaskAsyncEnumerable source14, IUniTaskAsyncEnumerable source15, Func resultSelector) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + this.source13 = source13; + this.source14 = source14; + this.source15 = source15; + + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _CombineLatest(source1, source2, source3, source4, source5, source6, source7, source8, source9, source10, source11, source12, source13, source14, source15, resultSelector, cancellationToken); + } + + class _CombineLatest : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action Completed1Delegate = Completed1; + static readonly Action Completed2Delegate = Completed2; + static readonly Action Completed3Delegate = Completed3; + static readonly Action Completed4Delegate = Completed4; + static readonly Action Completed5Delegate = Completed5; + static readonly Action Completed6Delegate = Completed6; + static readonly Action Completed7Delegate = Completed7; + static readonly Action Completed8Delegate = Completed8; + static readonly Action Completed9Delegate = Completed9; + static readonly Action Completed10Delegate = Completed10; + static readonly Action Completed11Delegate = Completed11; + static readonly Action Completed12Delegate = Completed12; + static readonly Action Completed13Delegate = Completed13; + static readonly Action Completed14Delegate = Completed14; + static readonly Action Completed15Delegate = Completed15; + const int CompleteCount = 15; + + readonly IUniTaskAsyncEnumerable source1; + readonly IUniTaskAsyncEnumerable source2; + readonly IUniTaskAsyncEnumerable source3; + readonly IUniTaskAsyncEnumerable source4; + readonly IUniTaskAsyncEnumerable source5; + readonly IUniTaskAsyncEnumerable source6; + readonly IUniTaskAsyncEnumerable source7; + readonly IUniTaskAsyncEnumerable source8; + readonly IUniTaskAsyncEnumerable source9; + readonly IUniTaskAsyncEnumerable source10; + readonly IUniTaskAsyncEnumerable source11; + readonly IUniTaskAsyncEnumerable source12; + readonly IUniTaskAsyncEnumerable source13; + readonly IUniTaskAsyncEnumerable source14; + readonly IUniTaskAsyncEnumerable source15; + + readonly Func resultSelector; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator1; + UniTask.Awaiter awaiter1; + bool hasCurrent1; + bool running1; + T1 current1; + + IUniTaskAsyncEnumerator enumerator2; + UniTask.Awaiter awaiter2; + bool hasCurrent2; + bool running2; + T2 current2; + + IUniTaskAsyncEnumerator enumerator3; + UniTask.Awaiter awaiter3; + bool hasCurrent3; + bool running3; + T3 current3; + + IUniTaskAsyncEnumerator enumerator4; + UniTask.Awaiter awaiter4; + bool hasCurrent4; + bool running4; + T4 current4; + + IUniTaskAsyncEnumerator enumerator5; + UniTask.Awaiter awaiter5; + bool hasCurrent5; + bool running5; + T5 current5; + + IUniTaskAsyncEnumerator enumerator6; + UniTask.Awaiter awaiter6; + bool hasCurrent6; + bool running6; + T6 current6; + + IUniTaskAsyncEnumerator enumerator7; + UniTask.Awaiter awaiter7; + bool hasCurrent7; + bool running7; + T7 current7; + + IUniTaskAsyncEnumerator enumerator8; + UniTask.Awaiter awaiter8; + bool hasCurrent8; + bool running8; + T8 current8; + + IUniTaskAsyncEnumerator enumerator9; + UniTask.Awaiter awaiter9; + bool hasCurrent9; + bool running9; + T9 current9; + + IUniTaskAsyncEnumerator enumerator10; + UniTask.Awaiter awaiter10; + bool hasCurrent10; + bool running10; + T10 current10; + + IUniTaskAsyncEnumerator enumerator11; + UniTask.Awaiter awaiter11; + bool hasCurrent11; + bool running11; + T11 current11; + + IUniTaskAsyncEnumerator enumerator12; + UniTask.Awaiter awaiter12; + bool hasCurrent12; + bool running12; + T12 current12; + + IUniTaskAsyncEnumerator enumerator13; + UniTask.Awaiter awaiter13; + bool hasCurrent13; + bool running13; + T13 current13; + + IUniTaskAsyncEnumerator enumerator14; + UniTask.Awaiter awaiter14; + bool hasCurrent14; + bool running14; + T14 current14; + + IUniTaskAsyncEnumerator enumerator15; + UniTask.Awaiter awaiter15; + bool hasCurrent15; + bool running15; + T15 current15; + + int completedCount; + bool syncRunning; + TResult result; + + public _CombineLatest(IUniTaskAsyncEnumerable source1, IUniTaskAsyncEnumerable source2, IUniTaskAsyncEnumerable source3, IUniTaskAsyncEnumerable source4, IUniTaskAsyncEnumerable source5, IUniTaskAsyncEnumerable source6, IUniTaskAsyncEnumerable source7, IUniTaskAsyncEnumerable source8, IUniTaskAsyncEnumerable source9, IUniTaskAsyncEnumerable source10, IUniTaskAsyncEnumerable source11, IUniTaskAsyncEnumerable source12, IUniTaskAsyncEnumerable source13, IUniTaskAsyncEnumerable source14, IUniTaskAsyncEnumerable source15, Func resultSelector, CancellationToken cancellationToken) + { + this.source1 = source1; + this.source2 = source2; + this.source3 = source3; + this.source4 = source4; + this.source5 = source5; + this.source6 = source6; + this.source7 = source7; + this.source8 = source8; + this.source9 = source9; + this.source10 = source10; + this.source11 = source11; + this.source12 = source12; + this.source13 = source13; + this.source14 = source14; + this.source15 = source15; + + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current => result; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + if (completedCount == CompleteCount) return CompletedTasks.False; + + if (enumerator1 == null) + { + enumerator1 = source1.GetAsyncEnumerator(cancellationToken); + enumerator2 = source2.GetAsyncEnumerator(cancellationToken); + enumerator3 = source3.GetAsyncEnumerator(cancellationToken); + enumerator4 = source4.GetAsyncEnumerator(cancellationToken); + enumerator5 = source5.GetAsyncEnumerator(cancellationToken); + enumerator6 = source6.GetAsyncEnumerator(cancellationToken); + enumerator7 = source7.GetAsyncEnumerator(cancellationToken); + enumerator8 = source8.GetAsyncEnumerator(cancellationToken); + enumerator9 = source9.GetAsyncEnumerator(cancellationToken); + enumerator10 = source10.GetAsyncEnumerator(cancellationToken); + enumerator11 = source11.GetAsyncEnumerator(cancellationToken); + enumerator12 = source12.GetAsyncEnumerator(cancellationToken); + enumerator13 = source13.GetAsyncEnumerator(cancellationToken); + enumerator14 = source14.GetAsyncEnumerator(cancellationToken); + enumerator15 = source15.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + + AGAIN: + syncRunning = true; + if (!running1) + { + running1 = true; + awaiter1 = enumerator1.MoveNextAsync().GetAwaiter(); + if (awaiter1.IsCompleted) + { + Completed1(this); + } + else + { + awaiter1.SourceOnCompleted(Completed1Delegate, this); + } + } + if (!running2) + { + running2 = true; + awaiter2 = enumerator2.MoveNextAsync().GetAwaiter(); + if (awaiter2.IsCompleted) + { + Completed2(this); + } + else + { + awaiter2.SourceOnCompleted(Completed2Delegate, this); + } + } + if (!running3) + { + running3 = true; + awaiter3 = enumerator3.MoveNextAsync().GetAwaiter(); + if (awaiter3.IsCompleted) + { + Completed3(this); + } + else + { + awaiter3.SourceOnCompleted(Completed3Delegate, this); + } + } + if (!running4) + { + running4 = true; + awaiter4 = enumerator4.MoveNextAsync().GetAwaiter(); + if (awaiter4.IsCompleted) + { + Completed4(this); + } + else + { + awaiter4.SourceOnCompleted(Completed4Delegate, this); + } + } + if (!running5) + { + running5 = true; + awaiter5 = enumerator5.MoveNextAsync().GetAwaiter(); + if (awaiter5.IsCompleted) + { + Completed5(this); + } + else + { + awaiter5.SourceOnCompleted(Completed5Delegate, this); + } + } + if (!running6) + { + running6 = true; + awaiter6 = enumerator6.MoveNextAsync().GetAwaiter(); + if (awaiter6.IsCompleted) + { + Completed6(this); + } + else + { + awaiter6.SourceOnCompleted(Completed6Delegate, this); + } + } + if (!running7) + { + running7 = true; + awaiter7 = enumerator7.MoveNextAsync().GetAwaiter(); + if (awaiter7.IsCompleted) + { + Completed7(this); + } + else + { + awaiter7.SourceOnCompleted(Completed7Delegate, this); + } + } + if (!running8) + { + running8 = true; + awaiter8 = enumerator8.MoveNextAsync().GetAwaiter(); + if (awaiter8.IsCompleted) + { + Completed8(this); + } + else + { + awaiter8.SourceOnCompleted(Completed8Delegate, this); + } + } + if (!running9) + { + running9 = true; + awaiter9 = enumerator9.MoveNextAsync().GetAwaiter(); + if (awaiter9.IsCompleted) + { + Completed9(this); + } + else + { + awaiter9.SourceOnCompleted(Completed9Delegate, this); + } + } + if (!running10) + { + running10 = true; + awaiter10 = enumerator10.MoveNextAsync().GetAwaiter(); + if (awaiter10.IsCompleted) + { + Completed10(this); + } + else + { + awaiter10.SourceOnCompleted(Completed10Delegate, this); + } + } + if (!running11) + { + running11 = true; + awaiter11 = enumerator11.MoveNextAsync().GetAwaiter(); + if (awaiter11.IsCompleted) + { + Completed11(this); + } + else + { + awaiter11.SourceOnCompleted(Completed11Delegate, this); + } + } + if (!running12) + { + running12 = true; + awaiter12 = enumerator12.MoveNextAsync().GetAwaiter(); + if (awaiter12.IsCompleted) + { + Completed12(this); + } + else + { + awaiter12.SourceOnCompleted(Completed12Delegate, this); + } + } + if (!running13) + { + running13 = true; + awaiter13 = enumerator13.MoveNextAsync().GetAwaiter(); + if (awaiter13.IsCompleted) + { + Completed13(this); + } + else + { + awaiter13.SourceOnCompleted(Completed13Delegate, this); + } + } + if (!running14) + { + running14 = true; + awaiter14 = enumerator14.MoveNextAsync().GetAwaiter(); + if (awaiter14.IsCompleted) + { + Completed14(this); + } + else + { + awaiter14.SourceOnCompleted(Completed14Delegate, this); + } + } + if (!running15) + { + running15 = true; + awaiter15 = enumerator15.MoveNextAsync().GetAwaiter(); + if (awaiter15.IsCompleted) + { + Completed15(this); + } + else + { + awaiter15.SourceOnCompleted(Completed15Delegate, this); + } + } + + if (!running1 || !running2 || !running3 || !running4 || !running5 || !running6 || !running7 || !running8 || !running9 || !running10 || !running11 || !running12 || !running13 || !running14 || !running15) + { + goto AGAIN; + } + syncRunning = false; + + return new UniTask(this, completionSource.Version); + } + + static void Completed1(object state) + { + var self = (_CombineLatest)state; + self.running1 = false; + + try + { + if (self.awaiter1.GetResult()) + { + self.hasCurrent1 = true; + self.current1 = self.enumerator1.Current; + goto SUCCESS; + } + else + { + self.running1 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running1 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running1 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter1 = self.enumerator1.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter1.SourceOnCompleted(Completed1Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed2(object state) + { + var self = (_CombineLatest)state; + self.running2 = false; + + try + { + if (self.awaiter2.GetResult()) + { + self.hasCurrent2 = true; + self.current2 = self.enumerator2.Current; + goto SUCCESS; + } + else + { + self.running2 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running2 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running2 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter2 = self.enumerator2.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter2.SourceOnCompleted(Completed2Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed3(object state) + { + var self = (_CombineLatest)state; + self.running3 = false; + + try + { + if (self.awaiter3.GetResult()) + { + self.hasCurrent3 = true; + self.current3 = self.enumerator3.Current; + goto SUCCESS; + } + else + { + self.running3 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running3 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running3 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter3 = self.enumerator3.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter3.SourceOnCompleted(Completed3Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed4(object state) + { + var self = (_CombineLatest)state; + self.running4 = false; + + try + { + if (self.awaiter4.GetResult()) + { + self.hasCurrent4 = true; + self.current4 = self.enumerator4.Current; + goto SUCCESS; + } + else + { + self.running4 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running4 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running4 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter4 = self.enumerator4.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter4.SourceOnCompleted(Completed4Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed5(object state) + { + var self = (_CombineLatest)state; + self.running5 = false; + + try + { + if (self.awaiter5.GetResult()) + { + self.hasCurrent5 = true; + self.current5 = self.enumerator5.Current; + goto SUCCESS; + } + else + { + self.running5 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running5 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running5 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter5 = self.enumerator5.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter5.SourceOnCompleted(Completed5Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed6(object state) + { + var self = (_CombineLatest)state; + self.running6 = false; + + try + { + if (self.awaiter6.GetResult()) + { + self.hasCurrent6 = true; + self.current6 = self.enumerator6.Current; + goto SUCCESS; + } + else + { + self.running6 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running6 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running6 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter6 = self.enumerator6.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter6.SourceOnCompleted(Completed6Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed7(object state) + { + var self = (_CombineLatest)state; + self.running7 = false; + + try + { + if (self.awaiter7.GetResult()) + { + self.hasCurrent7 = true; + self.current7 = self.enumerator7.Current; + goto SUCCESS; + } + else + { + self.running7 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running7 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running7 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter7 = self.enumerator7.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter7.SourceOnCompleted(Completed7Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed8(object state) + { + var self = (_CombineLatest)state; + self.running8 = false; + + try + { + if (self.awaiter8.GetResult()) + { + self.hasCurrent8 = true; + self.current8 = self.enumerator8.Current; + goto SUCCESS; + } + else + { + self.running8 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running8 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running8 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter8 = self.enumerator8.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter8.SourceOnCompleted(Completed8Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed9(object state) + { + var self = (_CombineLatest)state; + self.running9 = false; + + try + { + if (self.awaiter9.GetResult()) + { + self.hasCurrent9 = true; + self.current9 = self.enumerator9.Current; + goto SUCCESS; + } + else + { + self.running9 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running9 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running9 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter9 = self.enumerator9.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter9.SourceOnCompleted(Completed9Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed10(object state) + { + var self = (_CombineLatest)state; + self.running10 = false; + + try + { + if (self.awaiter10.GetResult()) + { + self.hasCurrent10 = true; + self.current10 = self.enumerator10.Current; + goto SUCCESS; + } + else + { + self.running10 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running10 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running10 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter10 = self.enumerator10.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter10.SourceOnCompleted(Completed10Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed11(object state) + { + var self = (_CombineLatest)state; + self.running11 = false; + + try + { + if (self.awaiter11.GetResult()) + { + self.hasCurrent11 = true; + self.current11 = self.enumerator11.Current; + goto SUCCESS; + } + else + { + self.running11 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running11 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running11 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter11 = self.enumerator11.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter11.SourceOnCompleted(Completed11Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed12(object state) + { + var self = (_CombineLatest)state; + self.running12 = false; + + try + { + if (self.awaiter12.GetResult()) + { + self.hasCurrent12 = true; + self.current12 = self.enumerator12.Current; + goto SUCCESS; + } + else + { + self.running12 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running12 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running12 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter12 = self.enumerator12.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter12.SourceOnCompleted(Completed12Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed13(object state) + { + var self = (_CombineLatest)state; + self.running13 = false; + + try + { + if (self.awaiter13.GetResult()) + { + self.hasCurrent13 = true; + self.current13 = self.enumerator13.Current; + goto SUCCESS; + } + else + { + self.running13 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running13 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running13 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter13 = self.enumerator13.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter13.SourceOnCompleted(Completed13Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed14(object state) + { + var self = (_CombineLatest)state; + self.running14 = false; + + try + { + if (self.awaiter14.GetResult()) + { + self.hasCurrent14 = true; + self.current14 = self.enumerator14.Current; + goto SUCCESS; + } + else + { + self.running14 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running14 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running14 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter14 = self.enumerator14.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter14.SourceOnCompleted(Completed14Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + static void Completed15(object state) + { + var self = (_CombineLatest)state; + self.running15 = false; + + try + { + if (self.awaiter15.GetResult()) + { + self.hasCurrent15 = true; + self.current15 = self.enumerator15.Current; + goto SUCCESS; + } + else + { + self.running15 = true; // as complete, no more call MoveNextAsync. + if (Interlocked.Increment(ref self.completedCount) == CompleteCount) + { + goto COMPLETE; + } + return; + } + } + catch (Exception ex) + { + self.running15 = true; // as complete, no more call MoveNextAsync. + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + SUCCESS: + if (!self.TrySetResult()) + { + if (self.syncRunning) return; + self.running15 = true; // as complete, no more call MoveNextAsync. + try + { + self.awaiter15 = self.enumerator15.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completedCount = CompleteCount; + self.completionSource.TrySetException(ex); + return; + } + + self.awaiter15.SourceOnCompleted(Completed15Delegate, self); + } + return; + COMPLETE: + self.completionSource.TrySetResult(false); + return; + } + + bool TrySetResult() + { + if (hasCurrent1 && hasCurrent2 && hasCurrent3 && hasCurrent4 && hasCurrent5 && hasCurrent6 && hasCurrent7 && hasCurrent8 && hasCurrent9 && hasCurrent10 && hasCurrent11 && hasCurrent12 && hasCurrent13 && hasCurrent14 && hasCurrent15) + { + result = resultSelector(current1, current2, current3, current4, current5, current6, current7, current8, current9, current10, current11, current12, current13, current14, current15); + completionSource.TrySetResult(true); + return true; + } + else + { + return false; + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator1 != null) + { + await enumerator1.DisposeAsync(); + } + if (enumerator2 != null) + { + await enumerator2.DisposeAsync(); + } + if (enumerator3 != null) + { + await enumerator3.DisposeAsync(); + } + if (enumerator4 != null) + { + await enumerator4.DisposeAsync(); + } + if (enumerator5 != null) + { + await enumerator5.DisposeAsync(); + } + if (enumerator6 != null) + { + await enumerator6.DisposeAsync(); + } + if (enumerator7 != null) + { + await enumerator7.DisposeAsync(); + } + if (enumerator8 != null) + { + await enumerator8.DisposeAsync(); + } + if (enumerator9 != null) + { + await enumerator9.DisposeAsync(); + } + if (enumerator10 != null) + { + await enumerator10.DisposeAsync(); + } + if (enumerator11 != null) + { + await enumerator11.DisposeAsync(); + } + if (enumerator12 != null) + { + await enumerator12.DisposeAsync(); + } + if (enumerator13 != null) + { + await enumerator13.DisposeAsync(); + } + if (enumerator14 != null) + { + await enumerator14.DisposeAsync(); + } + if (enumerator15 != null) + { + await enumerator15.DisposeAsync(); + } + } + } + } + +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/CombineLatest.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/CombineLatest.cs.meta new file mode 100644 index 00000000..4e8b1c34 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/CombineLatest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6cb07f6e88287e34d9b9301a572284a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Concat.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Concat.cs new file mode 100644 index 00000000..715795e8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Concat.cs @@ -0,0 +1,164 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Concat(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Concat(first, second); + } + } + + internal sealed class Concat : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + + public Concat(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + this.first = first; + this.second = second; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Concat(first, second, cancellationToken); + } + + sealed class _Concat : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + enum IteratingState + { + IteratingFirst, + IteratingSecond, + Complete + } + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + CancellationToken cancellationToken; + + IteratingState iteratingState; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public _Concat(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.cancellationToken = cancellationToken; + this.iteratingState = IteratingState.IteratingFirst; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (iteratingState == IteratingState.Complete) return CompletedTasks.False; + + completionSource.Reset(); + StartIterate(); + return new UniTask(this, completionSource.Version); + } + + void StartIterate() + { + if (enumerator == null) + { + if (iteratingState == IteratingState.IteratingFirst) + { + enumerator = first.GetAsyncEnumerator(cancellationToken); + } + else if (iteratingState == IteratingState.IteratingSecond) + { + enumerator = second.GetAsyncEnumerator(cancellationToken); + } + } + + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (awaiter.IsCompleted) + { + MoveNextCoreDelegate(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + + static void MoveNextCore(object state) + { + var self = (_Concat)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + if (self.iteratingState == IteratingState.IteratingFirst) + { + self.RunSecondAfterDisposeAsync().Forget(); + return; + } + + self.iteratingState = IteratingState.Complete; + self.completionSource.TrySetResult(false); + } + } + } + + async UniTaskVoid RunSecondAfterDisposeAsync() + { + try + { + await enumerator.DisposeAsync(); + enumerator = null; + awaiter = default; + iteratingState = IteratingState.IteratingSecond; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + + StartIterate(); + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Concat.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Concat.cs.meta new file mode 100644 index 00000000..6bfcf318 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Concat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7cb9e19c449127a459851a135ce7d527 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Contains.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Contains.cs new file mode 100644 index 00000000..a93f566c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Contains.cs @@ -0,0 +1,50 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ContainsAsync(this IUniTaskAsyncEnumerable source, TSource value, CancellationToken cancellationToken = default) + { + return ContainsAsync(source, value, EqualityComparer.Default, cancellationToken); + } + + public static UniTask ContainsAsync(this IUniTaskAsyncEnumerable source, TSource value, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return Contains.ContainsAsync(source, value, comparer, cancellationToken); + } + } + + internal static class Contains + { + internal static async UniTask ContainsAsync(IUniTaskAsyncEnumerable source, TSource value, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (comparer.Equals(value, e.Current)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Contains.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Contains.cs.meta new file mode 100644 index 00000000..9bd414b3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Contains.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36ab06d30f3223048b4f676e05431a7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Count.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Count.cs new file mode 100644 index 00000000..807b529b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Count.cs @@ -0,0 +1,144 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask CountAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Count.CountAsync(source, cancellationToken); + } + + public static UniTask CountAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Count.CountAsync(source, predicate, cancellationToken); + } + + public static UniTask CountAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Count.CountAwaitAsync(source, predicate, cancellationToken); + } + + public static UniTask CountAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Count.CountAwaitWithCancellationAsync(source, predicate, cancellationToken); + } + } + + internal static class Count + { + internal static async UniTask CountAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked { count++; } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask CountAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask CountAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask CountAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current, cancellationToken)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Count.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Count.cs.meta new file mode 100644 index 00000000..35db3324 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Count.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e606d38eed688574bb2ba89d983cc9bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Create.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Create.cs new file mode 100644 index 00000000..fa34774a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Create.cs @@ -0,0 +1,184 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Create(Func, CancellationToken, UniTask> create) + { + Error.ThrowArgumentNullException(create, nameof(create)); + return new Create(create); + } + } + + public interface IAsyncWriter + { + UniTask YieldAsync(T value); + } + + internal sealed class Create : IUniTaskAsyncEnumerable + { + readonly Func, CancellationToken, UniTask> create; + + public Create(Func, CancellationToken, UniTask> create) + { + this.create = create; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Create(create, cancellationToken); + } + + sealed class _Create : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly Func, CancellationToken, UniTask> create; + readonly CancellationToken cancellationToken; + + int state = -1; + AsyncWriter writer; + + public _Create(Func, CancellationToken, UniTask> create, CancellationToken cancellationToken) + { + this.create = create; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public T Current { get; private set; } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + writer.Dispose(); + return default; + } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + { + writer = new AsyncWriter(this); + RunWriterTask(create(writer, cancellationToken)).Forget(); + if (Volatile.Read(ref state) == -2) + { + return; // complete synchronously + } + state = 0; // wait YieldAsync, it set TrySetResult(true) + return; + } + case 0: + writer.SignalWriter(); + return; + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + } + + async UniTaskVoid RunWriterTask(UniTask task) + { + try + { + await task; + goto DONE; + } + catch (Exception ex) + { + Volatile.Write(ref state, -2); + completionSource.TrySetException(ex); + return; + } + + DONE: + Volatile.Write(ref state, -2); + completionSource.TrySetResult(false); + } + + public void SetResult(T value) + { + Current = value; + completionSource.TrySetResult(true); + } + } + + sealed class AsyncWriter : IUniTaskSource, IAsyncWriter, IDisposable + { + readonly _Create enumerator; + + UniTaskCompletionSourceCore core; + + public AsyncWriter(_Create enumerator) + { + this.enumerator = enumerator; + } + + public void Dispose() + { + var status = core.GetStatus(core.Version); + if (status == UniTaskStatus.Pending) + { + core.TrySetCanceled(); + } + } + + public void GetResult(short token) + { + core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTask YieldAsync(T value) + { + core.Reset(); + enumerator.SetResult(value); + return new UniTask(this, core.Version); + } + + public void SignalWriter() + { + core.TrySetResult(AsyncUnit.Default); + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Create.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Create.cs.meta new file mode 100644 index 00000000..5aba456f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Create.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0202f723469f93945afa063bfb440d15 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DefaultIfEmpty.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DefaultIfEmpty.cs new file mode 100644 index 00000000..3d21bd7c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DefaultIfEmpty.cs @@ -0,0 +1,142 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable DefaultIfEmpty(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new DefaultIfEmpty(source, default); + } + + public static IUniTaskAsyncEnumerable DefaultIfEmpty(this IUniTaskAsyncEnumerable source, TSource defaultValue) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new DefaultIfEmpty(source, defaultValue); + } + } + + internal sealed class DefaultIfEmpty : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly TSource defaultValue; + + public DefaultIfEmpty(IUniTaskAsyncEnumerable source, TSource defaultValue) + { + this.source = source; + this.defaultValue = defaultValue; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DefaultIfEmpty(source, defaultValue, cancellationToken); + } + + sealed class _DefaultIfEmpty : MoveNextSource, IUniTaskAsyncEnumerator + { + enum IteratingState : byte + { + Empty, + Iterating, + Completed + } + + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly TSource defaultValue; + CancellationToken cancellationToken; + + IteratingState iteratingState; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public _DefaultIfEmpty(IUniTaskAsyncEnumerable source, TSource defaultValue, CancellationToken cancellationToken) + { + this.source = source; + this.defaultValue = defaultValue; + this.cancellationToken = cancellationToken; + + this.iteratingState = IteratingState.Empty; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (iteratingState == IteratingState.Completed) + { + return CompletedTasks.False; + } + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void MoveNextCore(object state) + { + var self = (_DefaultIfEmpty)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.iteratingState = IteratingState.Iterating; + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + if (self.iteratingState == IteratingState.Empty) + { + self.iteratingState = IteratingState.Completed; + + self.Current = self.defaultValue; + self.completionSource.TrySetResult(true); + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DefaultIfEmpty.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DefaultIfEmpty.cs.meta new file mode 100644 index 00000000..5aa59939 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DefaultIfEmpty.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 19e437c039ad7e1478dbce1779ef8660 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Distinct.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Distinct.cs new file mode 100644 index 00000000..85bf795b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Distinct.cs @@ -0,0 +1,277 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source) + { + return Distinct(source, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Distinct(source, comparer); + } + + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source, Func keySelector) + { + return Distinct(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Distinct(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctAwait(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctAwait(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctAwaitWithCancellation(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctAwaitWithCancellation(source, keySelector, comparer); + } + } + + internal sealed class Distinct : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly IEqualityComparer comparer; + + public Distinct(IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + this.source = source; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Distinct(source, comparer, cancellationToken); + } + + class _Distinct : AsyncEnumeratorBase + { + readonly HashSet set; + + public _Distinct(IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (set.Add(v)) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class Distinct : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly IEqualityComparer comparer; + + public Distinct(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Distinct(source, keySelector, comparer, cancellationToken); + } + + class _Distinct : AsyncEnumeratorBase + { + readonly HashSet set; + readonly Func keySelector; + + public _Distinct(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + this.keySelector = keySelector; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (set.Add(keySelector(v))) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class DistinctAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DistinctAwait(source, keySelector, comparer, cancellationToken); + } + + class _DistinctAwait : AsyncEnumeratorAwaitSelectorBase + { + readonly HashSet set; + readonly Func> keySelector; + + public _DistinctAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + this.keySelector = keySelector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return keySelector(sourceCurrent); + } + + protected override bool TrySetCurrentCore(TKey awaitResult, out bool terminateIteration) + { + if (set.Add(awaitResult)) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = false; + return false; + } + } + } + } + + internal sealed class DistinctAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DistinctAwaitWithCancellation(source, keySelector, comparer, cancellationToken); + } + + class _DistinctAwaitWithCancellation : AsyncEnumeratorAwaitSelectorBase + { + readonly HashSet set; + readonly Func> keySelector; + + public _DistinctAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + this.keySelector = keySelector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return keySelector(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(TKey awaitResult, out bool terminateIteration) + { + if (set.Add(awaitResult)) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = false; + return false; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Distinct.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Distinct.cs.meta new file mode 100644 index 00000000..61804b7f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Distinct.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f09903be66e5d943b243d7c19cb3811 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DistinctUntilChanged.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DistinctUntilChanged.cs new file mode 100644 index 00000000..d91bef9f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DistinctUntilChanged.cs @@ -0,0 +1,662 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source) + { + return DistinctUntilChanged(source, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChanged(source, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source, Func keySelector) + { + return DistinctUntilChanged(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChanged(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctUntilChangedAwait(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChangedAwait(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctUntilChangedAwaitWithCancellation(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChangedAwaitWithCancellation(source, keySelector, comparer); + } + } + + internal sealed class DistinctUntilChanged : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly IEqualityComparer comparer; + + public DistinctUntilChanged(IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + this.source = source; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DistinctUntilChanged(source, comparer, cancellationToken); + } + + sealed class _DistinctUntilChanged : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly IEqualityComparer comparer; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Action moveNextAction; + + public _DistinctUntilChanged(IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case -3; + } + else + { + state = -3; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case -3: // first + if (awaiter.GetResult()) + { + Current = enumerator.Current; + goto CONTINUE; + } + else + { + goto DONE; + } + case 0: // normal + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + var v = enumerator.Current; + if (!comparer.Equals(Current, v)) + { + Current = v; + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + } + else + { + goto DONE; + } + case -2: + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class DistinctUntilChanged : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly IEqualityComparer comparer; + + public DistinctUntilChanged(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DistinctUntilChanged(source, keySelector, comparer, cancellationToken); + } + + sealed class _DistinctUntilChanged : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly IEqualityComparer comparer; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Action moveNextAction; + TKey prev; + + public _DistinctUntilChanged(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case -3; + } + else + { + state = -3; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case -3: // first + if (awaiter.GetResult()) + { + Current = enumerator.Current; + goto CONTINUE; + } + else + { + goto DONE; + } + case 0: // normal + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + var v = enumerator.Current; + var key = keySelector(v); + if (!comparer.Equals(prev, key)) + { + prev = key; + Current = v; + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + } + else + { + goto DONE; + } + case -2: + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class DistinctUntilChangedAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctUntilChangedAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DistinctUntilChangedAwait(source, keySelector, comparer, cancellationToken); + } + + sealed class _DistinctUntilChangedAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + TSource enumeratorCurrent; + TKey prev; + + public _DistinctUntilChangedAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case -3; + } + else + { + state = -3; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case -3: // first + if (awaiter.GetResult()) + { + Current = enumerator.Current; + goto CONTINUE; + } + else + { + goto DONE; + } + case 0: // normal + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + enumeratorCurrent = enumerator.Current; + awaiter2 = keySelector(enumeratorCurrent).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + var key = awaiter2.GetResult(); + if (!comparer.Equals(prev, key)) + { + prev = key; + Current = enumeratorCurrent; + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + case -2: + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class DistinctUntilChangedAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctUntilChangedAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _DistinctUntilChangedAwaitWithCancellation(source, keySelector, comparer, cancellationToken); + } + + sealed class _DistinctUntilChangedAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + TSource enumeratorCurrent; + TKey prev; + + public _DistinctUntilChangedAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case -3; + } + else + { + state = -3; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case -3: // first + if (awaiter.GetResult()) + { + Current = enumerator.Current; + goto CONTINUE; + } + else + { + goto DONE; + } + case 0: // normal + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + enumeratorCurrent = enumerator.Current; + awaiter2 = keySelector(enumeratorCurrent, cancellationToken).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + var key = awaiter2.GetResult(); + if (!comparer.Equals(prev, key)) + { + prev = key; + Current = enumeratorCurrent; + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + case -2: + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + return enumerator.DisposeAsync(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DistinctUntilChanged.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DistinctUntilChanged.cs.meta new file mode 100644 index 00000000..84cddf8d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/DistinctUntilChanged.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0351f6767df7e644b935d4d599968162 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Do.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Do.cs new file mode 100644 index 00000000..f6df368d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Do.cs @@ -0,0 +1,258 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Internal; +using Cysharp.Threading.Tasks.Linq; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return source.Do(onNext, null, null); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext, Action onError) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return source.Do(onNext, onError, null); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return source.Do(onNext, null, onCompleted); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return new Do(source, onNext, onError, onCompleted); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, IObserver observer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(observer, nameof(observer)); + + return source.Do(observer.OnNext, observer.OnError, observer.OnCompleted); // alloc delegate. + } + + // not yet impl. + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext, Func onError) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext, Func onError, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext, Func onError) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext, Func onError, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + } + + internal sealed class Do : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Action onNext; + readonly Action onError; + readonly Action onCompleted; + + public Do(IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted) + { + this.source = source; + this.onNext = onNext; + this.onError = onError; + this.onCompleted = onCompleted; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Do(source, onNext, onError, onCompleted, cancellationToken); + } + + sealed class _Do : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly Action onNext; + readonly Action onError; + readonly Action onCompleted; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public _Do(IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + this.source = source; + this.onNext = onNext; + this.onError = onError; + this.onCompleted = onCompleted; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + bool isCompleted = false; + try + { + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + isCompleted = awaiter.IsCompleted; + } + catch (Exception ex) + { + CallTrySetExceptionAfterNotification(ex); + return new UniTask(this, completionSource.Version); + } + + if (isCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + void CallTrySetExceptionAfterNotification(Exception ex) + { + if (onError != null) + { + try + { + onError(ex); + } + catch (Exception ex2) + { + completionSource.TrySetException(ex2); + return; + } + } + + completionSource.TrySetException(ex); + } + + bool TryGetResultWithNotification(UniTask.Awaiter awaiter, out T result) + { + try + { + result = awaiter.GetResult(); + return true; + } + catch (Exception ex) + { + CallTrySetExceptionAfterNotification(ex); + result = default; + return false; + } + } + + + static void MoveNextCore(object state) + { + var self = (_Do)state; + + if (self.TryGetResultWithNotification(self.awaiter, out var result)) + { + if (result) + { + var v = self.enumerator.Current; + + if (self.onNext != null) + { + try + { + self.onNext(v); + } + catch (Exception ex) + { + self.CallTrySetExceptionAfterNotification(ex); + } + } + + self.Current = v; + self.completionSource.TrySetResult(true); + } + else + { + if (self.onCompleted != null) + { + try + { + self.onCompleted(); + } + catch (Exception ex) + { + self.CallTrySetExceptionAfterNotification(ex); + return; + } + } + + self.completionSource.TrySetResult(false); + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Do.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Do.cs.meta new file mode 100644 index 00000000..766bbb5f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Do.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd83c8e12dedf75409b829b93146d130 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ElementAt.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ElementAt.cs new file mode 100644 index 00000000..930675e5 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ElementAt.cs @@ -0,0 +1,58 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ElementAtAsync(this IUniTaskAsyncEnumerable source, int index, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return ElementAt.ElementAtAsync(source, index, cancellationToken, false); + } + + public static UniTask ElementAtOrDefaultAsync(this IUniTaskAsyncEnumerable source, int index, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return ElementAt.ElementAtAsync(source, index, cancellationToken, true); + } + } + + internal static class ElementAt + { + public static async UniTask ElementAtAsync(IUniTaskAsyncEnumerable source, int index, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int i = 0; + while (await e.MoveNextAsync()) + { + if (i++ == index) + { + return e.Current; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.ArgumentOutOfRange(nameof(index)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ElementAt.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ElementAt.cs.meta new file mode 100644 index 00000000..fb0850b6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ElementAt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c835bd2dd8555234c8919c7b8ef3b69a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Empty.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Empty.cs new file mode 100644 index 00000000..2f5b3a49 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Empty.cs @@ -0,0 +1,47 @@ +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Empty() + { + return Cysharp.Threading.Tasks.Linq.Empty.Instance; + } + } + + internal class Empty : IUniTaskAsyncEnumerable + { + public static readonly IUniTaskAsyncEnumerable Instance = new Empty(); + + Empty() + { + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return _Empty.Instance; + } + + class _Empty : IUniTaskAsyncEnumerator + { + public static readonly IUniTaskAsyncEnumerator Instance = new _Empty(); + + _Empty() + { + } + + public T Current => default; + + public UniTask MoveNextAsync() + { + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Empty.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Empty.cs.meta new file mode 100644 index 00000000..bfa577ac --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Empty.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fa123ad6258abb4184721b719a13810 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Except.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Except.cs new file mode 100644 index 00000000..c4054823 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Except.cs @@ -0,0 +1,116 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Except(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Except(first, second, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Except(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Except(first, second, comparer); + } + } + + internal sealed class Except : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly IEqualityComparer comparer; + + public Except(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + this.first = first; + this.second = second; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Except(first, second, comparer, cancellationToken); + } + + class _Except : AsyncEnumeratorBase + { + static Action HashSetAsyncCoreDelegate = HashSetAsyncCore; + + readonly IEqualityComparer comparer; + readonly IUniTaskAsyncEnumerable second; + + HashSet set; + UniTask>.Awaiter awaiter; + + public _Except(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(first, cancellationToken) + { + this.second = second; + this.comparer = comparer; + } + + protected override bool OnFirstIteration() + { + if (set != null) return false; + + awaiter = second.ToHashSetAsync(cancellationToken).GetAwaiter(); + if (awaiter.IsCompleted) + { + set = awaiter.GetResult(); + SourceMoveNext(); + } + else + { + awaiter.SourceOnCompleted(HashSetAsyncCoreDelegate, this); + } + + return true; + } + + static void HashSetAsyncCore(object state) + { + var self = (_Except)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.set = result; + self.SourceMoveNext(); + } + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (set.Add(v)) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Except.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Except.cs.meta new file mode 100644 index 00000000..f61a1aab --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Except.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38c1c4129f59dcb49a5b864eaf4ec63c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/First.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/First.cs new file mode 100644 index 00000000..da5688b4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/First.cs @@ -0,0 +1,200 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask FirstAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return First.FirstAsync(source, cancellationToken, false); + } + + public static UniTask FirstAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.FirstAsync(source, predicate, cancellationToken, false); + } + + public static UniTask FirstAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.FirstAwaitAsync(source, predicate, cancellationToken, false); + } + + public static UniTask FirstAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.FirstAwaitWithCancellationAsync(source, predicate, cancellationToken, false); + } + + public static UniTask FirstOrDefaultAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return First.FirstAsync(source, cancellationToken, true); + } + + public static UniTask FirstOrDefaultAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.FirstAsync(source, predicate, cancellationToken, true); + } + + public static UniTask FirstOrDefaultAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.FirstAwaitAsync(source, predicate, cancellationToken, true); + } + + public static UniTask FirstOrDefaultAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.FirstAwaitWithCancellationAsync(source, predicate, cancellationToken, true); + } + } + + internal static class First + { + public static async UniTask FirstAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + if (await e.MoveNextAsync()) + { + return e.Current; + } + else + { + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask FirstAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (predicate(v)) + { + return v; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask FirstAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v)) + { + return v; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask FirstAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v, cancellationToken)) + { + return v; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/First.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/First.cs.meta new file mode 100644 index 00000000..6924307a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/First.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 417946e97e9eed84db6f840f57037ca6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ForEach.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ForEach.cs new file mode 100644 index 00000000..60f246dd --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ForEach.cs @@ -0,0 +1,193 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ForEachAsync(this IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.ForEachAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAsync(this IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.ForEachAsync(source, action, cancellationToken); + } + + /// Obsolete(Error), Use Use ForEachAwaitAsync instead. + [Obsolete("Use ForEachAwaitAsync instead.", true)] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static UniTask ForEachAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + throw new NotSupportedException("Use ForEachAwaitAsync instead."); + } + + /// Obsolete(Error), Use Use ForEachAwaitAsync instead. + [Obsolete("Use ForEachAwaitAsync instead.", true)] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static UniTask ForEachAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + throw new NotSupportedException("Use ForEachAwaitAsync instead."); + } + + public static UniTask ForEachAwaitAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.ForEachAwaitAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.ForEachAwaitAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.ForEachAwaitWithCancellationAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.ForEachAwaitWithCancellationAsync(source, action, cancellationToken); + } + } + + internal static class ForEach + { + public static async UniTask ForEachAsync(IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + action(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask ForEachAsync(IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int index = 0; + while (await e.MoveNextAsync()) + { + action(e.Current, checked(index++)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask ForEachAwaitAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + await action(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask ForEachAwaitAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int index = 0; + while (await e.MoveNextAsync()) + { + await action(e.Current, checked(index++)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask ForEachAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + await action(e.Current, cancellationToken); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask ForEachAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int index = 0; + while (await e.MoveNextAsync()) + { + await action(e.Current, checked(index++), cancellationToken); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ForEach.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ForEach.cs.meta new file mode 100644 index 00000000..53177562 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ForEach.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca8d7f8177ba16140920af405aea3fd4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupBy.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupBy.cs new file mode 100644 index 00000000..b9460ae4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupBy.cs @@ -0,0 +1,923 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + // Ix-Async returns IGrouping but it is competely waste, use standard IGrouping. + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + return new GroupBy(source, keySelector, x => x, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, x => x, comparer); + } + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + return new GroupBy(source, keySelector, elementSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, elementSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func, TResult> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupBy(source, keySelector, x => x, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, x => x, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupBy(source, keySelector, elementSelector, resultSelector, EqualityComparer.Default); + } + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, elementSelector, resultSelector, comparer); + } + + // await + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), comparer); + } + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + return new GroupByAwait(source, keySelector, elementSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, elementSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwait(source, keySelector, elementSelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, elementSelector, resultSelector, comparer); + } + + // with ct + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), comparer); + } + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, CancellationToken, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, resultSelector, comparer); + } + } + + internal sealed class GroupBy : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly IEqualityComparer comparer; + + public GroupBy(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupBy(source, keySelector, elementSelector, comparer, cancellationToken); + } + + sealed class _GroupBy : MoveNextSource, IUniTaskAsyncEnumerator> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public _GroupBy(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public IGrouping Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + Current = groupEnumerator.Current as IGrouping; + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupBy : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + + public GroupBy(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupBy(source, keySelector, elementSelector, resultSelector, comparer, cancellationToken); + } + + sealed class _GroupBy : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public _GroupBy(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + var current = groupEnumerator.Current; + Current = resultSelector(current.Key, current); + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwait : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + + public GroupByAwait(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupByAwait(source, keySelector, elementSelector, comparer, cancellationToken); + } + + sealed class _GroupByAwait : MoveNextSource, IUniTaskAsyncEnumerator> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public _GroupByAwait(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public IGrouping Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + Current = groupEnumerator.Current as IGrouping; + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupByAwait(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupByAwait(source, keySelector, elementSelector, resultSelector, comparer, cancellationToken); + } + + sealed class _GroupByAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + UniTask.Awaiter awaiter; + + public _GroupByAwait(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + var current = groupEnumerator.Current; + + awaiter = resultSelector(current.Key, current).GetAwaiter(); + if (awaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + awaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + static void ResultSelectCore(object state) + { + var self = (_GroupByAwait)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwaitWithCancellation : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + + public GroupByAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupByAwaitWithCancellation(source, keySelector, elementSelector, comparer, cancellationToken); + } + + sealed class _GroupByAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public _GroupByAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public IGrouping Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitWithCancellationAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + Current = groupEnumerator.Current as IGrouping; + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupByAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupByAwaitWithCancellation(source, keySelector, elementSelector, resultSelector, comparer, cancellationToken); + } + + sealed class _GroupByAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + UniTask.Awaiter awaiter; + + public _GroupByAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitWithCancellationAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + var current = groupEnumerator.Current; + + awaiter = resultSelector(current.Key, current, cancellationToken).GetAwaiter(); + if (awaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + awaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + static void ResultSelectCore(object state) + { + var self = (_GroupByAwaitWithCancellation)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupBy.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupBy.cs.meta new file mode 100644 index 00000000..14897018 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupBy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2de80df1cc8a1240ab0ee7badd334d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupJoin.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupJoin.cs new file mode 100644 index 00000000..607b2217 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupJoin.cs @@ -0,0 +1,612 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable GroupJoin(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupJoin(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new GroupJoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new GroupJoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new GroupJoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new GroupJoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + } + + internal sealed class GroupJoin : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + + public GroupJoin(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class _GroupJoin : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + + public _GroupJoin(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + lookup = await inner.ToLookupAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_GroupJoin)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + var outer = self.enumerator.Current; + var key = self.outerKeySelector(outer); + var values = self.lookup[key]; + + self.Current = self.resultSelector(outer, values); + self.completionSource.TrySetResult(true); + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class GroupJoinAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupJoinAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupJoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class _GroupJoinAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + readonly static Action OuterKeySelectCoreDelegate = OuterKeySelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + TOuter outerValue; + UniTask.Awaiter awaiter; + UniTask.Awaiter outerKeyAwaiter; + UniTask.Awaiter resultAwaiter; + + + public _GroupJoinAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + lookup = await inner.ToLookupAwaitAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_GroupJoinAwait)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + try + { + + self.outerValue = self.enumerator.Current; + self.outerKeyAwaiter = self.outerKeySelector(self.outerValue).GetAwaiter(); + if (self.outerKeyAwaiter.IsCompleted) + { + OuterKeySelectCore(self); + } + else + { + self.outerKeyAwaiter.SourceOnCompleted(OuterKeySelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void OuterKeySelectCore(object state) + { + var self = (_GroupJoinAwait)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var result)) + { + try + { + var values = self.lookup[result]; + self.resultAwaiter = self.resultSelector(self.outerValue, values).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultSelectCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + } + + static void ResultSelectCore(object state) + { + var self = (_GroupJoinAwait)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class GroupJoinAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupJoinAwaitWithCancellation(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _GroupJoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class _GroupJoinAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + readonly static Action OuterKeySelectCoreDelegate = OuterKeySelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + TOuter outerValue; + UniTask.Awaiter awaiter; + UniTask.Awaiter outerKeyAwaiter; + UniTask.Awaiter resultAwaiter; + + + public _GroupJoinAwaitWithCancellation(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + lookup = await inner.ToLookupAwaitWithCancellationAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_GroupJoinAwaitWithCancellation)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + try + { + + self.outerValue = self.enumerator.Current; + self.outerKeyAwaiter = self.outerKeySelector(self.outerValue, self.cancellationToken).GetAwaiter(); + if (self.outerKeyAwaiter.IsCompleted) + { + OuterKeySelectCore(self); + } + else + { + self.outerKeyAwaiter.SourceOnCompleted(OuterKeySelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void OuterKeySelectCore(object state) + { + var self = (_GroupJoinAwaitWithCancellation)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var result)) + { + try + { + var values = self.lookup[result]; + self.resultAwaiter = self.resultSelector(self.outerValue, values, self.cancellationToken).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultSelectCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + } + + static void ResultSelectCore(object state) + { + var self = (_GroupJoinAwaitWithCancellation)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupJoin.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupJoin.cs.meta new file mode 100644 index 00000000..f171ed19 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/GroupJoin.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7bf7759d03bf3f64190d3ae83b182c2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Intersect.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Intersect.cs new file mode 100644 index 00000000..3faf645f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Intersect.cs @@ -0,0 +1,117 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Intersect(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Intersect(first, second, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Intersect(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Intersect(first, second, comparer); + } + } + + internal sealed class Intersect : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly IEqualityComparer comparer; + + public Intersect(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + this.first = first; + this.second = second; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Intersect(first, second, comparer, cancellationToken); + } + + class _Intersect : AsyncEnumeratorBase + { + static Action HashSetAsyncCoreDelegate = HashSetAsyncCore; + + readonly IEqualityComparer comparer; + readonly IUniTaskAsyncEnumerable second; + + HashSet set; + UniTask>.Awaiter awaiter; + + public _Intersect(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(first, cancellationToken) + { + this.second = second; + this.comparer = comparer; + } + + protected override bool OnFirstIteration() + { + if (set != null) return false; + + awaiter = second.ToHashSetAsync(cancellationToken).GetAwaiter(); + if (awaiter.IsCompleted) + { + set = awaiter.GetResult(); + SourceMoveNext(); + } + else + { + awaiter.SourceOnCompleted(HashSetAsyncCoreDelegate, this); + } + + return true; + } + + static void HashSetAsyncCore(object state) + { + var self = (_Intersect)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.set = result; + self.SourceMoveNext(); + } + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + + if (set.Remove(v)) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Intersect.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Intersect.cs.meta new file mode 100644 index 00000000..28cf8e30 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Intersect.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93999a70f5d57134bbe971f3e988c4f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Join.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Join.cs new file mode 100644 index 00000000..2d80889e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Join.cs @@ -0,0 +1,728 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Join(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Join(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable JoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new JoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable JoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new JoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable JoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new JoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable JoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new JoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + } + + internal sealed class Join : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func resultSelector; + readonly IEqualityComparer comparer; + + public Join(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class _Join : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + TOuter currentOuterValue; + IEnumerator valueEnumerator; + + bool continueNext; + + public _Join(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateInnerHashSet().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateInnerHashSet() + { + try + { + lookup = await inner.ToLookupAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + LOOP: + if (valueEnumerator != null) + { + if (valueEnumerator.MoveNext()) + { + Current = resultSelector(currentOuterValue, valueEnumerator.Current); + goto TRY_SET_RESULT_TRUE; + } + else + { + valueEnumerator.Dispose(); + valueEnumerator = null; + } + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + + return; + + TRY_SET_RESULT_TRUE: + completionSource.TrySetResult(true); + } + + + static void MoveNextCore(object state) + { + var self = (_Join)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.currentOuterValue = self.enumerator.Current; + var key = self.outerKeySelector(self.currentOuterValue); + self.valueEnumerator = self.lookup[key].GetEnumerator(); + + if (self.continueNext) + { + return; + } + else + { + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (valueEnumerator != null) + { + valueEnumerator.Dispose(); + } + + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class JoinAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + + public JoinAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _JoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class _JoinAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + static readonly Action OuterSelectCoreDelegate = OuterSelectCore; + static readonly Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + TOuter currentOuterValue; + IEnumerator valueEnumerator; + + UniTask.Awaiter resultAwaiter; + UniTask.Awaiter outerKeyAwaiter; + + bool continueNext; + + public _JoinAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateInnerHashSet().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateInnerHashSet() + { + try + { + lookup = await inner.ToLookupAwaitAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + LOOP: + if (valueEnumerator != null) + { + if (valueEnumerator.MoveNext()) + { + resultAwaiter = resultSelector(currentOuterValue, valueEnumerator.Current).GetAwaiter(); + if (resultAwaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + valueEnumerator.Dispose(); + valueEnumerator = null; + } + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (_JoinAwait)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.currentOuterValue = self.enumerator.Current; + + self.outerKeyAwaiter = self.outerKeySelector(self.currentOuterValue).GetAwaiter(); + + if (self.outerKeyAwaiter.IsCompleted) + { + OuterSelectCore(self); + } + else + { + self.continueNext = false; + self.outerKeyAwaiter.SourceOnCompleted(OuterSelectCoreDelegate, self); + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + static void OuterSelectCore(object state) + { + var self = (_JoinAwait)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var key)) + { + self.valueEnumerator = self.lookup[key].GetEnumerator(); + + if (self.continueNext) + { + return; + } + else + { + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + static void ResultSelectCore(object state) + { + var self = (_JoinAwait)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (valueEnumerator != null) + { + valueEnumerator.Dispose(); + } + + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class JoinAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + + public JoinAwaitWithCancellation(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _JoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class _JoinAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + static readonly Action OuterSelectCoreDelegate = OuterSelectCore; + static readonly Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + TOuter currentOuterValue; + IEnumerator valueEnumerator; + + UniTask.Awaiter resultAwaiter; + UniTask.Awaiter outerKeyAwaiter; + + bool continueNext; + + public _JoinAwaitWithCancellation(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateInnerHashSet().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateInnerHashSet() + { + try + { + lookup = await inner.ToLookupAwaitWithCancellationAsync(innerKeySelector, comparer, cancellationToken: cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + LOOP: + if (valueEnumerator != null) + { + if (valueEnumerator.MoveNext()) + { + resultAwaiter = resultSelector(currentOuterValue, valueEnumerator.Current, cancellationToken).GetAwaiter(); + if (resultAwaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + valueEnumerator.Dispose(); + valueEnumerator = null; + } + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (_JoinAwaitWithCancellation)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.currentOuterValue = self.enumerator.Current; + + self.outerKeyAwaiter = self.outerKeySelector(self.currentOuterValue, self.cancellationToken).GetAwaiter(); + + if (self.outerKeyAwaiter.IsCompleted) + { + OuterSelectCore(self); + } + else + { + self.continueNext = false; + self.outerKeyAwaiter.SourceOnCompleted(OuterSelectCoreDelegate, self); + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + static void OuterSelectCore(object state) + { + var self = (_JoinAwaitWithCancellation)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var key)) + { + self.valueEnumerator = self.lookup[key].GetEnumerator(); + + if (self.continueNext) + { + return; + } + else + { + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + static void ResultSelectCore(object state) + { + var self = (_JoinAwaitWithCancellation)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (valueEnumerator != null) + { + valueEnumerator.Dispose(); + } + + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Join.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Join.cs.meta new file mode 100644 index 00000000..3ab1015a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Join.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc4ff8cb6d7c9a64896f2f082124d6b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Last.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Last.cs new file mode 100644 index 00000000..664bb27d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Last.cs @@ -0,0 +1,240 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask LastAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Last.LastAsync(source, cancellationToken, false); + } + + public static UniTask LastAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.LastAsync(source, predicate, cancellationToken, false); + } + + public static UniTask LastAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.LastAwaitAsync(source, predicate, cancellationToken, false); + } + + public static UniTask LastAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.LastAwaitWithCancellationAsync(source, predicate, cancellationToken, false); + } + + public static UniTask LastOrDefaultAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Last.LastAsync(source, cancellationToken, true); + } + + public static UniTask LastOrDefaultAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.LastAsync(source, predicate, cancellationToken, true); + } + + public static UniTask LastOrDefaultAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.LastAwaitAsync(source, predicate, cancellationToken, true); + } + + public static UniTask LastOrDefaultAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.LastAwaitWithCancellationAsync(source, predicate, cancellationToken, true); + } + } + + internal static class Last + { + public static async UniTask LastAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + if (defaultIfEmpty) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + + while (await e.MoveNextAsync()) + { + value = e.Current; + } + return value; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask LastAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (predicate(v)) + { + found = true; + value = v; + } + } + + if (defaultIfEmpty) + { + return value; + } + else + { + if (found) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask LastAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v)) + { + found = true; + value = v; + } + } + + if (defaultIfEmpty) + { + return value; + } + else + { + if (found) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask LastAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v, cancellationToken)) + { + found = true; + value = v; + } + } + + if (defaultIfEmpty) + { + return value; + } + else + { + if (found) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Last.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Last.cs.meta new file mode 100644 index 00000000..edfa124a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Last.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0ccc93be1387fa4a975f06310127c11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/LongCount.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/LongCount.cs new file mode 100644 index 00000000..78ae805f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/LongCount.cs @@ -0,0 +1,144 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask LongCountAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return LongCount.LongCountAsync(source, cancellationToken); + } + + public static UniTask LongCountAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return LongCount.LongCountAsync(source, predicate, cancellationToken); + } + + public static UniTask LongCountAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return LongCount.LongCountAwaitAsync(source, predicate, cancellationToken); + } + + public static UniTask LongCountAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return LongCount.LongCountAwaitWithCancellationAsync(source, predicate, cancellationToken); + } + } + + internal static class LongCount + { + internal static async UniTask LongCountAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked { count++; } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask LongCountAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask LongCountAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask LongCountAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current, cancellationToken)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/LongCount.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/LongCount.cs.meta new file mode 100644 index 00000000..862c2bcf --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/LongCount.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 198b39e58ced3ab4f97ccbe0916787d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Max.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Max.cs new file mode 100644 index 00000000..d244a15d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Max.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + } + + internal static partial class Max + { + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + TSource value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Max.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Max.cs.meta new file mode 100644 index 00000000..2125edf6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Max.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c8a118a6b664c441820b8a87d7f6e28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Merge.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Merge.cs new file mode 100644 index 00000000..b74bf252 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Merge.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Merge(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Merge(new [] { first, second }); + } + + public static IUniTaskAsyncEnumerable Merge(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IUniTaskAsyncEnumerable third) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(third, nameof(third)); + + return new Merge(new[] { first, second, third }); + } + + public static IUniTaskAsyncEnumerable Merge(this IEnumerable> sources) + { + return sources is IUniTaskAsyncEnumerable[] array + ? new Merge(array) + : new Merge(sources.ToArray()); + } + + public static IUniTaskAsyncEnumerable Merge(params IUniTaskAsyncEnumerable[] sources) + { + return new Merge(sources); + } + } + + internal sealed class Merge : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable[] sources; + + public Merge(IUniTaskAsyncEnumerable[] sources) + { + if (sources.Length <= 0) + { + Error.ThrowArgumentException("No source async enumerable to merge"); + } + this.sources = sources; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + => new _Merge(sources, cancellationToken); + + enum MergeSourceState + { + Pending, + Running, + Completed, + } + + sealed class _Merge : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action GetResultAtAction = GetResultAt; + + readonly int length; + readonly IUniTaskAsyncEnumerator[] enumerators; + readonly MergeSourceState[] states; + readonly Queue<(T, Exception, bool)> queuedResult = new Queue<(T, Exception, bool)>(); + readonly CancellationToken cancellationToken; + + int moveNextCompleted; + + public T Current { get; private set; } + + public _Merge(IUniTaskAsyncEnumerable[] sources, CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + length = sources.Length; + states = ArrayPool.Shared.Rent(length); + enumerators = ArrayPool>.Shared.Rent(length); + for (var i = 0; i < length; i++) + { + enumerators[i] = sources[i].GetAsyncEnumerator(cancellationToken); + states[i] = (int)MergeSourceState.Pending;; + } + } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + Interlocked.Exchange(ref moveNextCompleted, 0); + + if (HasQueuedResult() && Interlocked.CompareExchange(ref moveNextCompleted, 1, 0) == 0) + { + (T, Exception, bool) value; + lock (states) + { + value = queuedResult.Dequeue(); + } + var resultValue = value.Item1; + var exception = value.Item2; + var hasNext = value.Item3; + if (exception != null) + { + completionSource.TrySetException(exception); + } + else + { + Current = resultValue; + completionSource.TrySetResult(hasNext); + } + return new UniTask(this, completionSource.Version); + } + + for (var i = 0; i < length; i++) + { + lock (states) + { + if (states[i] == MergeSourceState.Pending) + { + states[i] = MergeSourceState.Running; + } + else + { + continue; + } + } + var awaiter = enumerators[i].MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + GetResultAt(i, awaiter); + } + else + { + awaiter.SourceOnCompleted(GetResultAtAction, StateTuple.Create(this, i, awaiter)); + } + } + return new UniTask(this, completionSource.Version); + } + + public async UniTask DisposeAsync() + { + for (var i = 0; i < length; i++) + { + await enumerators[i].DisposeAsync(); + } + + ArrayPool.Shared.Return(states, true); + ArrayPool>.Shared.Return(enumerators, true); + } + + static void GetResultAt(object state) + { + using (var tuple = (StateTuple<_Merge, int, UniTask.Awaiter>)state) + { + tuple.Item1.GetResultAt(tuple.Item2, tuple.Item3); + } + } + + void GetResultAt(int index, UniTask.Awaiter awaiter) + { + bool hasNext; + bool completedAll; + try + { + hasNext = awaiter.GetResult(); + } + catch (Exception ex) + { + if (Interlocked.CompareExchange(ref moveNextCompleted, 1, 0) == 0) + { + completionSource.TrySetException(ex); + } + else + { + lock (states) + { + queuedResult.Enqueue((default, ex, default)); + } + } + return; + } + + lock (states) + { + states[index] = hasNext ? MergeSourceState.Pending : MergeSourceState.Completed; + completedAll = !hasNext && IsCompletedAll(); + } + if (hasNext || completedAll) + { + if (Interlocked.CompareExchange(ref moveNextCompleted, 1, 0) == 0) + { + Current = enumerators[index].Current; + completionSource.TrySetResult(!completedAll); + } + else + { + lock (states) + { + queuedResult.Enqueue((enumerators[index].Current, null, !completedAll)); + } + } + } + } + + bool HasQueuedResult() + { + lock (states) + { + return queuedResult.Count > 0; + } + } + + bool IsCompletedAll() + { + lock (states) + { + for (var i = 0; i < length; i++) + { + if (states[i] != MergeSourceState.Completed) + { + return false; + } + } + } + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Merge.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Merge.cs.meta new file mode 100644 index 00000000..2f671f4c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Merge.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ca56812f160c45d0bacb4339819edf1a +timeCreated: 1694133666 \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Min.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Min.cs new file mode 100644 index 00000000..8768a86e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Min.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + } + + internal static partial class Min + { + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + TSource value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Min.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Min.cs.meta new file mode 100644 index 00000000..91378dc9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Min.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57ac9da21d3457849a8e45548290a508 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/MinMax.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/MinMax.cs new file mode 100644 index 00000000..aae3541b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/MinMax.cs @@ -0,0 +1,3763 @@ +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.MinAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.MinAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + } + + internal static partial class Min + { + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MinAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + } + + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.MaxAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.MaxAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + } + + internal static partial class Max + { + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask MaxAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + } + +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/MinMax.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/MinMax.cs.meta new file mode 100644 index 00000000..3856b65f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/MinMax.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d6da02d9ab970e4999daf7147d98e36 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Never.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Never.cs new file mode 100644 index 00000000..2dbce711 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Never.cs @@ -0,0 +1,56 @@ +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Never() + { + return Cysharp.Threading.Tasks.Linq.Never.Instance; + } + } + + internal class Never : IUniTaskAsyncEnumerable + { + public static readonly IUniTaskAsyncEnumerable Instance = new Never(); + + Never() + { + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Never(cancellationToken); + } + + class _Never : IUniTaskAsyncEnumerator + { + CancellationToken cancellationToken; + + public _Never(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public T Current => default; + + public UniTask MoveNextAsync() + { + var tcs = new UniTaskCompletionSource(); + + cancellationToken.Register(state => + { + var task = (UniTaskCompletionSource)state; + task.TrySetCanceled(cancellationToken); + }, tcs); + + return tcs.Task; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Never.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Never.cs.meta new file mode 100644 index 00000000..ba9d358c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Never.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b307c3d3be71a94da251564bcdefa3d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OfType.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OfType.cs new file mode 100644 index 00000000..fea8069f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OfType.cs @@ -0,0 +1,61 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable OfType(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new OfType(source); + } + } + + internal sealed class OfType : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public OfType(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _OfType(source, cancellationToken); + } + + class _OfType : AsyncEnumeratorBase + { + public _OfType(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (SourceCurrent is TResult castCurent) + { + Current = castCurent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OfType.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OfType.cs.meta new file mode 100644 index 00000000..6ace53fd --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OfType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 111ffe87a7d700442a9ef5af554b252c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OrderBy.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OrderBy.cs new file mode 100644 index 00000000..d0c379fe --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OrderBy.cs @@ -0,0 +1,558 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + #region OrderBy_OrderByDescending + + public static IUniTaskOrderedAsyncEnumerable OrderBy(this IUniTaskAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerable(source, keySelector, Comparer.Default, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderBy(this IUniTaskAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerable(source, keySelector, comparer, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, Comparer.Default, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, comparer, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, Comparer.Default, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, comparer, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescending(this IUniTaskAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerable(source, keySelector, Comparer.Default, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescending(this IUniTaskAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerable(source, keySelector, comparer, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, Comparer.Default, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, comparer, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, Comparer.Default, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, comparer, true, null); + } + + #endregion + + #region ThenBy_ThenByDescending + + public static IUniTaskOrderedAsyncEnumerable ThenBy(this IUniTaskOrderedAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenBy(this IUniTaskOrderedAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescending(this IUniTaskOrderedAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescending(this IUniTaskOrderedAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, true); + } + + #endregion + } + + internal abstract class AsyncEnumerableSorter + { + internal abstract UniTask ComputeKeysAsync(TElement[] elements, int count); + + internal abstract int CompareKeys(int index1, int index2); + + internal async UniTask SortAsync(TElement[] elements, int count) + { + await ComputeKeysAsync(elements, count); + + int[] map = new int[count]; + for (int i = 0; i < count; i++) map[i] = i; + QuickSort(map, 0, count - 1); + return map; + } + + void QuickSort(int[] map, int left, int right) + { + do + { + int i = left; + int j = right; + int x = map[i + ((j - i) >> 1)]; + do + { + while (i < map.Length && CompareKeys(x, map[i]) > 0) i++; + while (j >= 0 && CompareKeys(x, map[j]) < 0) j--; + if (i > j) break; + if (i < j) + { + int temp = map[i]; + map[i] = map[j]; + map[j] = temp; + } + i++; + j--; + } while (i <= j); + if (j - left <= right - i) + { + if (left < j) QuickSort(map, left, j); + left = i; + } + else + { + if (i < right) QuickSort(map, i, right); + right = j; + } + } while (left < right); + } + } + + internal class SyncSelectorAsyncEnumerableSorter : AsyncEnumerableSorter + { + readonly Func keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly AsyncEnumerableSorter next; + TKey[] keys; + + internal SyncSelectorAsyncEnumerableSorter(Func keySelector, IComparer comparer, bool descending, AsyncEnumerableSorter next) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.next = next; + } + + internal override async UniTask ComputeKeysAsync(TElement[] elements, int count) + { + keys = new TKey[count]; + for (int i = 0; i < count; i++) keys[i] = keySelector(elements[i]); + if (next != null) await next.ComputeKeysAsync(elements, count); + } + + internal override int CompareKeys(int index1, int index2) + { + int c = comparer.Compare(keys[index1], keys[index2]); + if (c == 0) + { + if (next == null) return index1 - index2; + return next.CompareKeys(index1, index2); + } + return descending ? -c : c; + } + } + + internal class AsyncSelectorEnumerableSorter : AsyncEnumerableSorter + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly AsyncEnumerableSorter next; + TKey[] keys; + + internal AsyncSelectorEnumerableSorter(Func> keySelector, IComparer comparer, bool descending, AsyncEnumerableSorter next) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.next = next; + } + + internal override async UniTask ComputeKeysAsync(TElement[] elements, int count) + { + keys = new TKey[count]; + for (int i = 0; i < count; i++) keys[i] = await keySelector(elements[i]); + if (next != null) await next.ComputeKeysAsync(elements, count); + } + + internal override int CompareKeys(int index1, int index2) + { + int c = comparer.Compare(keys[index1], keys[index2]); + if (c == 0) + { + if (next == null) return index1 - index2; + return next.CompareKeys(index1, index2); + } + return descending ? -c : c; + } + } + + internal class AsyncSelectorWithCancellationEnumerableSorter : AsyncEnumerableSorter + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly AsyncEnumerableSorter next; + CancellationToken cancellationToken; + TKey[] keys; + + internal AsyncSelectorWithCancellationEnumerableSorter(Func> keySelector, IComparer comparer, bool descending, AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.next = next; + this.cancellationToken = cancellationToken; + } + + internal override async UniTask ComputeKeysAsync(TElement[] elements, int count) + { + keys = new TKey[count]; + for (int i = 0; i < count; i++) keys[i] = await keySelector(elements[i], cancellationToken); + if (next != null) await next.ComputeKeysAsync(elements, count); + } + + internal override int CompareKeys(int index1, int index2) + { + int c = comparer.Compare(keys[index1], keys[index2]); + if (c == 0) + { + if (next == null) return index1 - index2; + return next.CompareKeys(index1, index2); + } + return descending ? -c : c; + } + } + + internal abstract class OrderedAsyncEnumerable : IUniTaskOrderedAsyncEnumerable + { + protected readonly IUniTaskAsyncEnumerable source; + + public OrderedAsyncEnumerable(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func keySelector, IComparer comparer, bool descending) + { + return new OrderedAsyncEnumerable(source, keySelector, comparer, descending, this); + } + + public IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending) + { + return new OrderedAsyncEnumerableAwait(source, keySelector, comparer, descending, this); + } + + public IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending) + { + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, comparer, descending, this); + } + + internal abstract AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken); + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _OrderedAsyncEnumerator(this, cancellationToken); + } + + class _OrderedAsyncEnumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + protected readonly OrderedAsyncEnumerable parent; + CancellationToken cancellationToken; + TElement[] buffer; + int[] map; + int index; + + public _OrderedAsyncEnumerator(OrderedAsyncEnumerable parent, CancellationToken cancellationToken) + { + this.parent = parent; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TElement Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (map == null) + { + completionSource.Reset(); + CreateSortSource().Forget(); + return new UniTask(this, completionSource.Version); + } + + if (index < buffer.Length) + { + Current = buffer[map[index++]]; + return CompletedTasks.True; + } + else + { + return CompletedTasks.False; + } + } + + async UniTaskVoid CreateSortSource() + { + try + { + buffer = await parent.source.ToArrayAsync(); + if (buffer.Length == 0) + { + completionSource.TrySetResult(false); + return; + } + + var sorter = parent.GetAsyncEnumerableSorter(null, cancellationToken); + map = await sorter.SortAsync(buffer, buffer.Length); + sorter = null; + + // set first value + Current = buffer[map[index++]]; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + completionSource.TrySetResult(true); + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return default; + } + } + } + + internal class OrderedAsyncEnumerable : OrderedAsyncEnumerable + { + readonly Func keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly OrderedAsyncEnumerable parent; + + public OrderedAsyncEnumerable(IUniTaskAsyncEnumerable source, Func keySelector, IComparer comparer, bool descending, OrderedAsyncEnumerable parent) + : base(source) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.parent = parent; + } + + internal override AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + AsyncEnumerableSorter sorter = new SyncSelectorAsyncEnumerableSorter(keySelector, comparer, descending, next); + if (parent != null) sorter = parent.GetAsyncEnumerableSorter(sorter, cancellationToken); + return sorter; + } + } + + internal class OrderedAsyncEnumerableAwait : OrderedAsyncEnumerable + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly OrderedAsyncEnumerable parent; + + public OrderedAsyncEnumerableAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer, bool descending, OrderedAsyncEnumerable parent) + : base(source) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.parent = parent; + } + + internal override AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + AsyncEnumerableSorter sorter = new AsyncSelectorEnumerableSorter(keySelector, comparer, descending, next); + if (parent != null) sorter = parent.GetAsyncEnumerableSorter(sorter, cancellationToken); + return sorter; + } + } + + internal class OrderedAsyncEnumerableAwaitWithCancellation : OrderedAsyncEnumerable + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly OrderedAsyncEnumerable parent; + + public OrderedAsyncEnumerableAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer, bool descending, OrderedAsyncEnumerable parent) + : base(source) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.parent = parent; + } + + internal override AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + AsyncEnumerableSorter sorter = new AsyncSelectorWithCancellationEnumerableSorter(keySelector, comparer, descending, next, cancellationToken); + if (parent != null) sorter = parent.GetAsyncEnumerableSorter(sorter, cancellationToken); + return sorter; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OrderBy.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OrderBy.cs.meta new file mode 100644 index 00000000..5c6b3e4a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/OrderBy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 413883ceff8546143bdf200aafa4b8f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Pairwise.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Pairwise.cs new file mode 100644 index 00000000..5d44a9e8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Pairwise.cs @@ -0,0 +1,128 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable<(TSource, TSource)> Pairwise(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Pairwise(source); + } + } + + internal sealed class Pairwise : IUniTaskAsyncEnumerable<(TSource, TSource)> + { + readonly IUniTaskAsyncEnumerable source; + + public Pairwise(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator<(TSource, TSource)> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Pairwise(source, cancellationToken); + } + + sealed class _Pairwise : MoveNextSource, IUniTaskAsyncEnumerator<(TSource, TSource)> + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + TSource prev; + bool isFirst; + + public _Pairwise(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public (TSource, TSource) Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + isFirst = true; + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_Pairwise)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.isFirst) + { + self.isFirst = false; + self.prev = self.enumerator.Current; + self.SourceMoveNext(); // run again. okay to use recursive(only one more). + } + else + { + var p = self.prev; + self.prev = self.enumerator.Current; + self.Current = (p, self.prev); + self.completionSource.TrySetResult(true); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Pairwise.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Pairwise.cs.meta new file mode 100644 index 00000000..727b8cf4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Pairwise.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cddbf051d2a88f549986c468b23214af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Publish.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Publish.cs new file mode 100644 index 00000000..d218c0f2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Publish.cs @@ -0,0 +1,173 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IConnectableUniTaskAsyncEnumerable Publish(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Publish(source); + } + } + + internal sealed class Publish : IConnectableUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly CancellationTokenSource cancellationTokenSource; + + TriggerEvent trigger; + IUniTaskAsyncEnumerator enumerator; + IDisposable connectedDisposable; + bool isCompleted; + + public Publish(IUniTaskAsyncEnumerable source) + { + this.source = source; + this.cancellationTokenSource = new CancellationTokenSource(); + } + + public IDisposable Connect() + { + if (connectedDisposable != null) return connectedDisposable; + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationTokenSource.Token); + } + + ConsumeEnumerator().Forget(); + + connectedDisposable = new ConnectDisposable(cancellationTokenSource); + return connectedDisposable; + } + + async UniTaskVoid ConsumeEnumerator() + { + try + { + try + { + while (await enumerator.MoveNextAsync()) + { + trigger.SetResult(enumerator.Current); + } + trigger.SetCompleted(); + } + catch (Exception ex) + { + trigger.SetError(ex); + } + } + finally + { + isCompleted = true; + await enumerator.DisposeAsync(); + } + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Publish(this, cancellationToken); + } + + sealed class ConnectDisposable : IDisposable + { + readonly CancellationTokenSource cancellationTokenSource; + + public ConnectDisposable(CancellationTokenSource cancellationTokenSource) + { + this.cancellationTokenSource = cancellationTokenSource; + } + + public void Dispose() + { + this.cancellationTokenSource.Cancel(); + } + } + + sealed class _Publish : MoveNextSource, IUniTaskAsyncEnumerator, ITriggerHandler + { + static readonly Action CancelDelegate = OnCanceled; + + readonly Publish parent; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool isDisposed; + + public _Publish(Publish parent, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) return; + + this.parent = parent; + this.cancellationToken = cancellationToken; + + if (cancellationToken.CanBeCanceled) + { + this.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(CancelDelegate, this); + } + + parent.trigger.Add(this); + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (parent.isCompleted) return CompletedTasks.False; + + completionSource.Reset(); + return new UniTask(this, completionSource.Version); + } + + static void OnCanceled(object state) + { + var self = (_Publish)state; + self.completionSource.TrySetCanceled(self.cancellationToken); + self.DisposeAsync().Forget(); + } + + public UniTask DisposeAsync() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + cancellationTokenRegistration.Dispose(); + parent.trigger.Remove(this); + } + + return default; + } + + public void OnNext(TSource value) + { + Current = value; + completionSource.TrySetResult(true); + } + + public void OnCanceled(CancellationToken cancellationToken) + { + completionSource.TrySetCanceled(cancellationToken); + } + + public void OnCompleted() + { + completionSource.TrySetResult(false); + } + + public void OnError(Exception ex) + { + completionSource.TrySetException(ex); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Publish.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Publish.cs.meta new file mode 100644 index 00000000..f3a81ba3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Publish.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93c684d1e88c09d4e89b79437d97b810 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Queue.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Queue.cs new file mode 100644 index 00000000..b5c221fb --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Queue.cs @@ -0,0 +1,103 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Queue(this IUniTaskAsyncEnumerable source) + { + return new QueueOperator(source); + } + } + + internal sealed class QueueOperator : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public QueueOperator(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Queue(source, cancellationToken); + } + + sealed class _Queue : IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken; + + Channel channel; + IUniTaskAsyncEnumerator channelEnumerator; + IUniTaskAsyncEnumerator sourceEnumerator; + bool channelClosed; + + public _Queue(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public TSource Current => channelEnumerator.Current; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + channel = Channel.CreateSingleConsumerUnbounded(); + + channelEnumerator = channel.Reader.ReadAllAsync().GetAsyncEnumerator(cancellationToken); + + ConsumeAll(this, sourceEnumerator, channel).Forget(); + } + + return channelEnumerator.MoveNextAsync(); + } + + static async UniTaskVoid ConsumeAll(_Queue self, IUniTaskAsyncEnumerator enumerator, ChannelWriter writer) + { + try + { + while (await enumerator.MoveNextAsync()) + { + writer.TryWrite(enumerator.Current); + } + writer.TryComplete(); + } + catch (Exception ex) + { + writer.TryComplete(ex); + } + finally + { + self.channelClosed = true; + await enumerator.DisposeAsync(); + } + } + + public async UniTask DisposeAsync() + { + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + if (channelEnumerator != null) + { + await channelEnumerator.DisposeAsync(); + } + + if (!channelClosed) + { + channelClosed = true; + channel.Writer.TryComplete(new OperationCanceledException()); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Queue.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Queue.cs.meta new file mode 100644 index 00000000..35f3fab2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Queue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b7ea1bcf9dbebb042bc99c7816249e02 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Range.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Range.cs new file mode 100644 index 00000000..24a795d1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Range.cs @@ -0,0 +1,75 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Range(int start, int count) + { + if (count < 0) throw Error.ArgumentOutOfRange(nameof(count)); + + var end = (long)start + count - 1L; + if (end > int.MaxValue) throw Error.ArgumentOutOfRange(nameof(count)); + + if (count == 0) UniTaskAsyncEnumerable.Empty(); + + return new Cysharp.Threading.Tasks.Linq.Range(start, count); + } + } + + internal class Range : IUniTaskAsyncEnumerable + { + readonly int start; + readonly int end; + + public Range(int start, int count) + { + this.start = start; + this.end = start + count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Range(start, end, cancellationToken); + } + + class _Range : IUniTaskAsyncEnumerator + { + readonly int start; + readonly int end; + int current; + CancellationToken cancellationToken; + + public _Range(int start, int end, CancellationToken cancellationToken) + { + this.start = start; + this.end = end; + this.cancellationToken = cancellationToken; + + this.current = start - 1; + } + + public int Current => current; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + current++; + + if (current != end) + { + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Range.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Range.cs.meta new file mode 100644 index 00000000..36272fcf --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Range.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d826418a813498648b10542d0a5fb173 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Repeat.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Repeat.cs new file mode 100644 index 00000000..db90a1ae --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Repeat.cs @@ -0,0 +1,68 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Repeat(TElement element, int count) + { + if (count < 0) throw Error.ArgumentOutOfRange(nameof(count)); + + return new Repeat(element, count); + } + } + + internal class Repeat : IUniTaskAsyncEnumerable + { + readonly TElement element; + readonly int count; + + public Repeat(TElement element, int count) + { + this.element = element; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Repeat(element, count, cancellationToken); + } + + class _Repeat : IUniTaskAsyncEnumerator + { + readonly TElement element; + readonly int count; + int remaining; + CancellationToken cancellationToken; + + public _Repeat(TElement element, int count, CancellationToken cancellationToken) + { + this.element = element; + this.count = count; + this.cancellationToken = cancellationToken; + + this.remaining = count; + } + + public TElement Current => element; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (remaining-- != 0) + { + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Repeat.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Repeat.cs.meta new file mode 100644 index 00000000..693d5790 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Repeat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3819a3925165a674d80ee848c8600379 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Return.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Return.cs new file mode 100644 index 00000000..ba8fa8df --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Return.cs @@ -0,0 +1,63 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Return(TValue value) + { + return new Return(value); + } + } + + internal class Return : IUniTaskAsyncEnumerable + { + readonly TValue value; + + public Return(TValue value) + { + this.value = value; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Return(value, cancellationToken); + } + + class _Return : IUniTaskAsyncEnumerator + { + readonly TValue value; + CancellationToken cancellationToken; + + bool called; + + public _Return(TValue value, CancellationToken cancellationToken) + { + this.value = value; + this.cancellationToken = cancellationToken; + this.called = false; + } + + public TValue Current => value; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (!called) + { + called = true; + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Return.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Return.cs.meta new file mode 100644 index 00000000..ad264d0d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Return.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4313cd8ecf705e44f9064ce46e293c2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Reverse.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Reverse.cs new file mode 100644 index 00000000..48d43181 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Reverse.cs @@ -0,0 +1,78 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Reverse(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return new Reverse(source); + } + } + + internal sealed class Reverse : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public Reverse(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Reverse(source, cancellationToken); + } + + sealed class _Reverse : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken; + + TSource[] array; + int index; + + public _Reverse(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + // after consumed array, don't use await so allow async(not require UniTaskCompletionSourceCore). + public async UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (array == null) + { + array = await source.ToArrayAsync(cancellationToken); + index = array.Length - 1; + } + + if (index != -1) + { + Current = array[index]; + --index; + return true; + } + else + { + return false; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Reverse.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Reverse.cs.meta new file mode 100644 index 00000000..4a28306a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Reverse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2769e65c729b4f4ca6af9826d9c7b90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Select.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Select.cs new file mode 100644 index 00000000..50e9cec9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Select.cs @@ -0,0 +1,760 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Select(this IUniTaskAsyncEnumerable source, Func selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.Select(source, selector); + } + + public static IUniTaskAsyncEnumerable Select(this IUniTaskAsyncEnumerable source, Func selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectInt(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwait(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectAwait(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwait(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectIntAwait(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectAwaitWithCancellation(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectIntAwaitWithCancellation(source, selector); + } + } + + internal sealed class Select : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func selector; + + public Select(IUniTaskAsyncEnumerable source, Func selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Select(source, selector, cancellationToken); + } + + sealed class _Select : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func selector; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Action moveNextAction; + + public _Select(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + this.source = source; + this.selector = selector; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = selector(enumerator.Current); + goto CONTINUE; + } + else + { + goto DONE; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class SelectInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func selector; + + public SelectInt(IUniTaskAsyncEnumerable source, Func selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Select(source, selector, cancellationToken); + } + + sealed class _Select : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func selector; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Action moveNextAction; + int index; + + public _Select(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + this.source = source; + this.selector = selector; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = selector(enumerator.Current, checked(index++)); + goto CONTINUE; + } + else + { + goto DONE; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class SelectAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectAwait(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectAwait(source, selector, cancellationToken); + } + + sealed class _SelectAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + + public _SelectAwait(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + this.source = source; + this.selector = selector; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + awaiter2 = selector(enumerator.Current).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + Current = awaiter2.GetResult(); + goto CONTINUE; + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class SelectIntAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectIntAwait(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectAwait(source, selector, cancellationToken); + } + + sealed class _SelectAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + int index; + + public _SelectAwait(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + this.source = source; + this.selector = selector; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + awaiter2 = selector(enumerator.Current, checked(index++)).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + Current = awaiter2.GetResult(); + goto CONTINUE; + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class SelectAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectAwaitWithCancellation(source, selector, cancellationToken); + } + + sealed class _SelectAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + + public _SelectAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + this.source = source; + this.selector = selector; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + awaiter2 = selector(enumerator.Current, cancellationToken).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + Current = awaiter2.GetResult(); + goto CONTINUE; + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class SelectIntAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectAwaitWithCancellation(source, selector, cancellationToken); + } + + sealed class _SelectAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + int index; + + public _SelectAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + this.source = source; + this.selector = selector; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + awaiter2 = selector(enumerator.Current, checked(index++), cancellationToken).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + Current = awaiter2.GetResult(); + goto CONTINUE; + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Select.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Select.cs.meta new file mode 100644 index 00000000..476e9723 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Select.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc68e598ca44a134b988dfaf5e53bfba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SelectMany.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SelectMany.cs new file mode 100644 index 00000000..6cad2a50 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SelectMany.cs @@ -0,0 +1,892 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectMany(source, selector, (x, y) => y); + } + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectMany(source, selector, (x, y) => y); + } + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> collectionSelector, Func resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectMany(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> collectionSelector, Func resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectMany(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwait(source, selector, (x, y) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwait(source, selector, (x, y) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwait(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwait(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwaitWithCancellation(source, selector, (x, y, c) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwaitWithCancellation(source, selector, (x, y, c) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwaitWithCancellation(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwaitWithCancellation(source, collectionSelector, resultSelector); + } + } + + internal sealed class SelectMany : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector1; + readonly Func> selector2; + readonly Func resultSelector; + + public SelectMany(IUniTaskAsyncEnumerable source, Func> selector, Func resultSelector) + { + this.source = source; + this.selector1 = selector; + this.selector2 = null; + this.resultSelector = resultSelector; + } + + public SelectMany(IUniTaskAsyncEnumerable source, Func> selector, Func resultSelector) + { + this.source = source; + this.selector1 = null; + this.selector2 = selector; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectMany(source, selector1, selector2, resultSelector, cancellationToken); + } + + sealed class _SelectMany : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action sourceMoveNextCoreDelegate = SourceMoveNextCore; + static readonly Action selectedSourceMoveNextCoreDelegate = SeletedSourceMoveNextCore; + static readonly Action selectedEnumeratorDisposeAsyncCoreDelegate = SelectedEnumeratorDisposeAsyncCore; + + readonly IUniTaskAsyncEnumerable source; + + readonly Func> selector1; + readonly Func> selector2; + readonly Func resultSelector; + CancellationToken cancellationToken; + + TSource sourceCurrent; + int sourceIndex; + IUniTaskAsyncEnumerator sourceEnumerator; + IUniTaskAsyncEnumerator selectedEnumerator; + UniTask.Awaiter sourceAwaiter; + UniTask.Awaiter selectedAwaiter; + UniTask.Awaiter selectedDisposeAsyncAwaiter; + + public _SelectMany(IUniTaskAsyncEnumerable source, Func> selector1, Func> selector2, Func resultSelector, CancellationToken cancellationToken) + { + this.source = source; + this.selector1 = selector1; + this.selector2 = selector2; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + // iterate selected field + if (selectedEnumerator != null) + { + MoveNextSelected(); + } + else + { + // iterate source field + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + } + MoveNextSource(); + } + + return new UniTask(this, completionSource.Version); + } + + void MoveNextSource() + { + try + { + sourceAwaiter = sourceEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (sourceAwaiter.IsCompleted) + { + SourceMoveNextCore(this); + } + else + { + sourceAwaiter.SourceOnCompleted(sourceMoveNextCoreDelegate, this); + } + } + + void MoveNextSelected() + { + try + { + selectedAwaiter = selectedEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (selectedAwaiter.IsCompleted) + { + SeletedSourceMoveNextCore(this); + } + else + { + selectedAwaiter.SourceOnCompleted(selectedSourceMoveNextCoreDelegate, this); + } + } + + static void SourceMoveNextCore(object state) + { + var self = (_SelectMany)state; + + if (self.TryGetResult(self.sourceAwaiter, out var result)) + { + if (result) + { + try + { + self.sourceCurrent = self.sourceEnumerator.Current; + if (self.selector1 != null) + { + self.selectedEnumerator = self.selector1(self.sourceCurrent).GetAsyncEnumerator(self.cancellationToken); + } + else + { + self.selectedEnumerator = self.selector2(self.sourceCurrent, checked(self.sourceIndex++)).GetAsyncEnumerator(self.cancellationToken); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + self.MoveNextSelected(); // iterated selected source. + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SeletedSourceMoveNextCore(object state) + { + var self = (_SelectMany)state; + + if (self.TryGetResult(self.selectedAwaiter, out var result)) + { + if (result) + { + try + { + self.Current = self.resultSelector(self.sourceCurrent, self.selectedEnumerator.Current); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + self.completionSource.TrySetResult(true); + } + else + { + // dispose selected source and try iterate source. + try + { + self.selectedDisposeAsyncAwaiter = self.selectedEnumerator.DisposeAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + if (self.selectedDisposeAsyncAwaiter.IsCompleted) + { + SelectedEnumeratorDisposeAsyncCore(self); + } + else + { + self.selectedDisposeAsyncAwaiter.SourceOnCompleted(selectedEnumeratorDisposeAsyncCoreDelegate, self); + } + } + } + } + + static void SelectedEnumeratorDisposeAsyncCore(object state) + { + var self = (_SelectMany)state; + + if (self.TryGetResult(self.selectedDisposeAsyncAwaiter)) + { + self.selectedEnumerator = null; + self.selectedAwaiter = default; + + self.MoveNextSource(); // iterate next source + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (selectedEnumerator != null) + { + await selectedEnumerator.DisposeAsync(); + } + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class SelectManyAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + + public SelectManyAwait(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = selector; + this.selector2 = null; + this.resultSelector = resultSelector; + } + + public SelectManyAwait(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = null; + this.selector2 = selector; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectManyAwait(source, selector1, selector2, resultSelector, cancellationToken); + } + + sealed class _SelectManyAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action sourceMoveNextCoreDelegate = SourceMoveNextCore; + static readonly Action selectedSourceMoveNextCoreDelegate = SeletedSourceMoveNextCore; + static readonly Action selectedEnumeratorDisposeAsyncCoreDelegate = SelectedEnumeratorDisposeAsyncCore; + static readonly Action selectorAwaitCoreDelegate = SelectorAwaitCore; + static readonly Action resultSelectorAwaitCoreDelegate = ResultSelectorAwaitCore; + + readonly IUniTaskAsyncEnumerable source; + + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + CancellationToken cancellationToken; + + TSource sourceCurrent; + int sourceIndex; + IUniTaskAsyncEnumerator sourceEnumerator; + IUniTaskAsyncEnumerator selectedEnumerator; + UniTask.Awaiter sourceAwaiter; + UniTask.Awaiter selectedAwaiter; + UniTask.Awaiter selectedDisposeAsyncAwaiter; + + // await additional + UniTask>.Awaiter collectionSelectorAwaiter; + UniTask.Awaiter resultSelectorAwaiter; + + public _SelectManyAwait(IUniTaskAsyncEnumerable source, Func>> selector1, Func>> selector2, Func> resultSelector, CancellationToken cancellationToken) + { + this.source = source; + this.selector1 = selector1; + this.selector2 = selector2; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + // iterate selected field + if (selectedEnumerator != null) + { + MoveNextSelected(); + } + else + { + // iterate source field + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + } + MoveNextSource(); + } + + return new UniTask(this, completionSource.Version); + } + + void MoveNextSource() + { + try + { + sourceAwaiter = sourceEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (sourceAwaiter.IsCompleted) + { + SourceMoveNextCore(this); + } + else + { + sourceAwaiter.SourceOnCompleted(sourceMoveNextCoreDelegate, this); + } + } + + void MoveNextSelected() + { + try + { + selectedAwaiter = selectedEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (selectedAwaiter.IsCompleted) + { + SeletedSourceMoveNextCore(this); + } + else + { + selectedAwaiter.SourceOnCompleted(selectedSourceMoveNextCoreDelegate, this); + } + } + + static void SourceMoveNextCore(object state) + { + var self = (_SelectManyAwait)state; + + if (self.TryGetResult(self.sourceAwaiter, out var result)) + { + if (result) + { + try + { + self.sourceCurrent = self.sourceEnumerator.Current; + + if (self.selector1 != null) + { + self.collectionSelectorAwaiter = self.selector1(self.sourceCurrent).GetAwaiter(); + } + else + { + self.collectionSelectorAwaiter = self.selector2(self.sourceCurrent, checked(self.sourceIndex++)).GetAwaiter(); + } + + if (self.collectionSelectorAwaiter.IsCompleted) + { + SelectorAwaitCore(self); + } + else + { + self.collectionSelectorAwaiter.SourceOnCompleted(selectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SeletedSourceMoveNextCore(object state) + { + var self = (_SelectManyAwait)state; + + if (self.TryGetResult(self.selectedAwaiter, out var result)) + { + if (result) + { + try + { + self.resultSelectorAwaiter = self.resultSelector(self.sourceCurrent, self.selectedEnumerator.Current).GetAwaiter(); + if (self.resultSelectorAwaiter.IsCompleted) + { + ResultSelectorAwaitCore(self); + } + else + { + self.resultSelectorAwaiter.SourceOnCompleted(resultSelectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + // dispose selected source and try iterate source. + try + { + self.selectedDisposeAsyncAwaiter = self.selectedEnumerator.DisposeAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + if (self.selectedDisposeAsyncAwaiter.IsCompleted) + { + SelectedEnumeratorDisposeAsyncCore(self); + } + else + { + self.selectedDisposeAsyncAwaiter.SourceOnCompleted(selectedEnumeratorDisposeAsyncCoreDelegate, self); + } + } + } + } + + static void SelectedEnumeratorDisposeAsyncCore(object state) + { + var self = (_SelectManyAwait)state; + + if (self.TryGetResult(self.selectedDisposeAsyncAwaiter)) + { + self.selectedEnumerator = null; + self.selectedAwaiter = default; + + self.MoveNextSource(); // iterate next source + } + } + + static void SelectorAwaitCore(object state) + { + var self = (_SelectManyAwait)state; + + if (self.TryGetResult(self.collectionSelectorAwaiter, out var result)) + { + self.selectedEnumerator = result.GetAsyncEnumerator(self.cancellationToken); + self.MoveNextSelected(); // iterated selected source. + } + } + + static void ResultSelectorAwaitCore(object state) + { + var self = (_SelectManyAwait)state; + + if (self.TryGetResult(self.resultSelectorAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (selectedEnumerator != null) + { + await selectedEnumerator.DisposeAsync(); + } + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class SelectManyAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + + public SelectManyAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = selector; + this.selector2 = null; + this.resultSelector = resultSelector; + } + + public SelectManyAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = null; + this.selector2 = selector; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SelectManyAwaitWithCancellation(source, selector1, selector2, resultSelector, cancellationToken); + } + + sealed class _SelectManyAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action sourceMoveNextCoreDelegate = SourceMoveNextCore; + static readonly Action selectedSourceMoveNextCoreDelegate = SeletedSourceMoveNextCore; + static readonly Action selectedEnumeratorDisposeAsyncCoreDelegate = SelectedEnumeratorDisposeAsyncCore; + static readonly Action selectorAwaitCoreDelegate = SelectorAwaitCore; + static readonly Action resultSelectorAwaitCoreDelegate = ResultSelectorAwaitCore; + + readonly IUniTaskAsyncEnumerable source; + + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + CancellationToken cancellationToken; + + TSource sourceCurrent; + int sourceIndex; + IUniTaskAsyncEnumerator sourceEnumerator; + IUniTaskAsyncEnumerator selectedEnumerator; + UniTask.Awaiter sourceAwaiter; + UniTask.Awaiter selectedAwaiter; + UniTask.Awaiter selectedDisposeAsyncAwaiter; + + // await additional + UniTask>.Awaiter collectionSelectorAwaiter; + UniTask.Awaiter resultSelectorAwaiter; + + public _SelectManyAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func>> selector1, Func>> selector2, Func> resultSelector, CancellationToken cancellationToken) + { + this.source = source; + this.selector1 = selector1; + this.selector2 = selector2; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + // iterate selected field + if (selectedEnumerator != null) + { + MoveNextSelected(); + } + else + { + // iterate source field + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + } + MoveNextSource(); + } + + return new UniTask(this, completionSource.Version); + } + + void MoveNextSource() + { + try + { + sourceAwaiter = sourceEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (sourceAwaiter.IsCompleted) + { + SourceMoveNextCore(this); + } + else + { + sourceAwaiter.SourceOnCompleted(sourceMoveNextCoreDelegate, this); + } + } + + void MoveNextSelected() + { + try + { + selectedAwaiter = selectedEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (selectedAwaiter.IsCompleted) + { + SeletedSourceMoveNextCore(this); + } + else + { + selectedAwaiter.SourceOnCompleted(selectedSourceMoveNextCoreDelegate, this); + } + } + + static void SourceMoveNextCore(object state) + { + var self = (_SelectManyAwaitWithCancellation)state; + + if (self.TryGetResult(self.sourceAwaiter, out var result)) + { + if (result) + { + try + { + self.sourceCurrent = self.sourceEnumerator.Current; + + if (self.selector1 != null) + { + self.collectionSelectorAwaiter = self.selector1(self.sourceCurrent, self.cancellationToken).GetAwaiter(); + } + else + { + self.collectionSelectorAwaiter = self.selector2(self.sourceCurrent, checked(self.sourceIndex++), self.cancellationToken).GetAwaiter(); + } + + if (self.collectionSelectorAwaiter.IsCompleted) + { + SelectorAwaitCore(self); + } + else + { + self.collectionSelectorAwaiter.SourceOnCompleted(selectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SeletedSourceMoveNextCore(object state) + { + var self = (_SelectManyAwaitWithCancellation)state; + + if (self.TryGetResult(self.selectedAwaiter, out var result)) + { + if (result) + { + try + { + self.resultSelectorAwaiter = self.resultSelector(self.sourceCurrent, self.selectedEnumerator.Current, self.cancellationToken).GetAwaiter(); + if (self.resultSelectorAwaiter.IsCompleted) + { + ResultSelectorAwaitCore(self); + } + else + { + self.resultSelectorAwaiter.SourceOnCompleted(resultSelectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + // dispose selected source and try iterate source. + try + { + self.selectedDisposeAsyncAwaiter = self.selectedEnumerator.DisposeAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + if (self.selectedDisposeAsyncAwaiter.IsCompleted) + { + SelectedEnumeratorDisposeAsyncCore(self); + } + else + { + self.selectedDisposeAsyncAwaiter.SourceOnCompleted(selectedEnumeratorDisposeAsyncCoreDelegate, self); + } + } + } + } + + static void SelectedEnumeratorDisposeAsyncCore(object state) + { + var self = (_SelectManyAwaitWithCancellation)state; + + if (self.TryGetResult(self.selectedDisposeAsyncAwaiter)) + { + self.selectedEnumerator = null; + self.selectedAwaiter = default; + + self.MoveNextSource(); // iterate next source + } + } + + static void SelectorAwaitCore(object state) + { + var self = (_SelectManyAwaitWithCancellation)state; + + if (self.TryGetResult(self.collectionSelectorAwaiter, out var result)) + { + self.selectedEnumerator = result.GetAsyncEnumerator(self.cancellationToken); + self.MoveNextSelected(); // iterated selected source. + } + } + + static void ResultSelectorAwaitCore(object state) + { + var self = (_SelectManyAwaitWithCancellation)state; + + if (self.TryGetResult(self.resultSelectorAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (selectedEnumerator != null) + { + await selectedEnumerator.DisposeAsync(); + } + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SelectMany.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SelectMany.cs.meta new file mode 100644 index 00000000..a8dbbaf6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SelectMany.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d81862f0eb12680479ccaaf2ac319d24 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SequenceEqual.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SequenceEqual.cs new file mode 100644 index 00000000..9512ea7d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SequenceEqual.cs @@ -0,0 +1,87 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask SequenceEqualAsync(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, CancellationToken cancellationToken = default) + { + return SequenceEqualAsync(first, second, EqualityComparer.Default, cancellationToken); + } + + public static UniTask SequenceEqualAsync(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return SequenceEqual.SequenceEqualAsync(first, second, comparer, cancellationToken); + } + } + + internal static class SequenceEqual + { + internal static async UniTask SequenceEqualAsync(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var e1 = first.GetAsyncEnumerator(cancellationToken); + try + { + var e2 = second.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + if (await e1.MoveNextAsync()) + { + if (await e2.MoveNextAsync()) + { + if (comparer.Equals(e1.Current, e2.Current)) + { + continue; + } + else + { + return false; + } + } + else + { + // e2 is finished, but e1 has value + return false; + } + } + else + { + // e1 is finished, e2? + if (await e2.MoveNextAsync()) + { + return false; + } + else + { + return true; + } + } + } + } + finally + { + if (e2 != null) + { + await e2.DisposeAsync(); + } + } + } + finally + { + if (e1 != null) + { + await e1.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SequenceEqual.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SequenceEqual.cs.meta new file mode 100644 index 00000000..ee2b75c2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SequenceEqual.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b382772aba6128842928cdb6b2e034b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Single.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Single.cs new file mode 100644 index 00000000..30df1b3d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Single.cs @@ -0,0 +1,230 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask SingleAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return SingleOperator.SingleAsync(source, cancellationToken, false); + } + + public static UniTask SingleAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.SingleAsync(source, predicate, cancellationToken, false); + } + + public static UniTask SingleAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.SingleAwaitAsync(source, predicate, cancellationToken, false); + } + + public static UniTask SingleAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.SingleAwaitWithCancellationAsync(source, predicate, cancellationToken, false); + } + + public static UniTask SingleOrDefaultAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return SingleOperator.SingleAsync(source, cancellationToken, true); + } + + public static UniTask SingleOrDefaultAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.SingleAsync(source, predicate, cancellationToken, true); + } + + public static UniTask SingleOrDefaultAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.SingleAwaitAsync(source, predicate, cancellationToken, true); + } + + public static UniTask SingleOrDefaultAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.SingleAwaitWithCancellationAsync(source, predicate, cancellationToken, true); + } + } + + internal static class SingleOperator + { + public static async UniTask SingleAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + if (await e.MoveNextAsync()) + { + var v = e.Current; + if (!await e.MoveNextAsync()) + { + return v; + } + + throw Error.MoreThanOneElement(); + } + else + { + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask SingleAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (predicate(v)) + { + if (found) + { + throw Error.MoreThanOneElement(); + } + else + { + found = true; + value = v; + } + } + } + + if (found || defaultIfEmpty) + { + return value; + } + + throw Error.NoElements(); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask SingleAwaitAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v)) + { + if (found) + { + throw Error.MoreThanOneElement(); + } + else + { + found = true; + value = v; + } + } + } + + if (found || defaultIfEmpty) + { + return value; + } + + throw Error.NoElements(); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask SingleAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v, cancellationToken)) + { + if (found) + { + throw Error.MoreThanOneElement(); + } + else + { + found = true; + value = v; + } + } + } + + if (found || defaultIfEmpty) + { + return value; + } + + throw Error.NoElements(); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Single.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Single.cs.meta new file mode 100644 index 00000000..c053dfd7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Single.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1bcd3928b90472e43a3a92c3ba708967 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Skip.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Skip.cs new file mode 100644 index 00000000..6f4831d1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Skip.cs @@ -0,0 +1,69 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Skip(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Skip(source, count); + } + } + + internal sealed class Skip : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public Skip(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Skip(source, count, cancellationToken); + } + + sealed class _Skip : AsyncEnumeratorBase + { + readonly int count; + + int index; + + public _Skip(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.count = count; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (count <= checked(index++)) + { + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + else + { + result = false; + return true; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Skip.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Skip.cs.meta new file mode 100644 index 00000000..25ad847b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Skip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c46b6c7dce0cb049a73c81084c75154 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipLast.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipLast.cs new file mode 100644 index 00000000..9d127b87 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipLast.cs @@ -0,0 +1,159 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable SkipLast(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + // non skip. + if (count <= 0) + { + return source; + } + + return new SkipLast(source, count); + } + } + + internal sealed class SkipLast : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public SkipLast(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipLast(source, count, cancellationToken); + } + + sealed class _SkipLast : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Queue queue; + + bool continueNext; + + public _SkipLast(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + queue = new Queue(); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (_SkipLast)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.queue.Count == self.count) + { + self.continueNext = false; + + var deq = self.queue.Dequeue(); + self.Current = deq; + self.queue.Enqueue(self.enumerator.Current); + + self.completionSource.TrySetResult(true); + } + else + { + self.queue.Enqueue(self.enumerator.Current); + + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipLast.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipLast.cs.meta new file mode 100644 index 00000000..06b1ede4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipLast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: df1d7f44d4fe7754f972c9e0b6fa72d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntil.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntil.cs new file mode 100644 index 00000000..5a707bb3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntil.cs @@ -0,0 +1,187 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable SkipUntil(this IUniTaskAsyncEnumerable source, UniTask other) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new SkipUntil(source, other, null); + } + + public static IUniTaskAsyncEnumerable SkipUntil(this IUniTaskAsyncEnumerable source, Func other) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(other)); + + return new SkipUntil(source, default, other); + } + } + + internal sealed class SkipUntil : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly UniTask other; + readonly Func other2; + + public SkipUntil(IUniTaskAsyncEnumerable source, UniTask other, Func other2) + { + this.source = source; + this.other = other; + this.other2 = other2; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + if (other2 != null) + { + return new _SkipUntil(source, this.other2(cancellationToken), cancellationToken); + } + else + { + return new _SkipUntil(source, this.other, cancellationToken); + } + } + + sealed class _SkipUntil : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action CancelDelegate1 = OnCanceled1; + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken1; + + bool completed; + CancellationTokenRegistration cancellationTokenRegistration1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + bool continueNext; + Exception exception; + + public _SkipUntil(IUniTaskAsyncEnumerable source, UniTask other, CancellationToken cancellationToken1) + { + this.source = source; + this.cancellationToken1 = cancellationToken1; + if (cancellationToken1.CanBeCanceled) + { + this.cancellationTokenRegistration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(CancelDelegate1, this); + } + + TaskTracker.TrackActiveTask(this, 3); + RunOther(other).Forget(); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (exception != null) + { + return UniTask.FromException(exception); + } + + if (cancellationToken1.IsCancellationRequested) + { + return UniTask.FromCanceled(cancellationToken1); + } + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken1); + } + completionSource.Reset(); + + if (completed) + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_SkipUntil)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + if (self.continueNext) + { + self.SourceMoveNext(); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + async UniTaskVoid RunOther(UniTask other) + { + try + { + await other; + completed = true; + SourceMoveNext(); + } + catch (Exception ex) + { + exception = ex; + completionSource.TrySetException(ex); + } + } + + static void OnCanceled1(object state) + { + var self = (_SkipUntil)state; + self.completionSource.TrySetCanceled(self.cancellationToken1); + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + cancellationTokenRegistration1.Dispose(); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntil.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntil.cs.meta new file mode 100644 index 00000000..0772ed01 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de932d79c8d9f3841a066d05ff29edc9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntilCanceled.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntilCanceled.cs new file mode 100644 index 00000000..f4c96798 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntilCanceled.cs @@ -0,0 +1,173 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable SkipUntilCanceled(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new SkipUntilCanceled(source, cancellationToken); + } + } + + internal sealed class SkipUntilCanceled : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly CancellationToken cancellationToken; + + public SkipUntilCanceled(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipUntilCanceled(source, this.cancellationToken, cancellationToken); + } + + sealed class _SkipUntilCanceled : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action CancelDelegate1 = OnCanceled1; + static readonly Action CancelDelegate2 = OnCanceled2; + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken1; + CancellationToken cancellationToken2; + CancellationTokenRegistration cancellationTokenRegistration1; + CancellationTokenRegistration cancellationTokenRegistration2; + + int isCanceled; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + bool continueNext; + + public _SkipUntilCanceled(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken1, CancellationToken cancellationToken2) + { + this.source = source; + this.cancellationToken1 = cancellationToken1; + this.cancellationToken2 = cancellationToken2; + if (cancellationToken1.CanBeCanceled) + { + this.cancellationTokenRegistration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(CancelDelegate1, this); + } + if (cancellationToken1 != cancellationToken2 && cancellationToken2.CanBeCanceled) + { + this.cancellationTokenRegistration2 = cancellationToken2.RegisterWithoutCaptureExecutionContext(CancelDelegate2, this); + } + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (enumerator == null) + { + if (cancellationToken1.IsCancellationRequested) isCanceled = 1; + if (cancellationToken2.IsCancellationRequested) isCanceled = 1; + enumerator = source.GetAsyncEnumerator(cancellationToken2); // use only AsyncEnumerator provided token. + } + completionSource.Reset(); + + if (isCanceled != 0) + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_SkipUntilCanceled)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + if (self.continueNext) + { + self.SourceMoveNext(); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void OnCanceled1(object state) + { + var self = (_SkipUntilCanceled)state; + if (self.isCanceled == 0) + { + if (Interlocked.Increment(ref self.isCanceled) == 1) + { + self.cancellationTokenRegistration2.Dispose(); + self.SourceMoveNext(); + } + } + } + + static void OnCanceled2(object state) + { + var self = (_SkipUntilCanceled)state; + if (self.isCanceled == 0) + { + if (Interlocked.Increment(ref self.isCanceled) == 1) + { + self.cancellationTokenRegistration2.Dispose(); + self.SourceMoveNext(); + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + cancellationTokenRegistration1.Dispose(); + cancellationTokenRegistration2.Dispose(); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntilCanceled.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntilCanceled.cs.meta new file mode 100644 index 00000000..9f67181d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipUntilCanceled.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b1a778aef7150d47b93a49aa1bc34ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipWhile.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipWhile.cs new file mode 100644 index 00000000..771a2e25 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipWhile.cs @@ -0,0 +1,379 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable SkipWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhile(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileIntAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileAwaitWithCancellation(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileIntAwaitWithCancellation(source, predicate); + } + } + + internal sealed class SkipWhile : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public SkipWhile(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipWhile(source, predicate, cancellationToken); + } + + class _SkipWhile : AsyncEnumeratorBase + { + Func predicate; + + public _SkipWhile(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate == null || !predicate(SourceCurrent)) + { + predicate = null; + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class SkipWhileInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public SkipWhileInt(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipWhileInt(source, predicate, cancellationToken); + } + + class _SkipWhileInt : AsyncEnumeratorBase + { + Func predicate; + int index; + + public _SkipWhileInt(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate == null || !predicate(SourceCurrent, checked(index++))) + { + predicate = null; + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class SkipWhileAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipWhileAwait(source, predicate, cancellationToken); + } + + class _SkipWhileAwait : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public _SkipWhileAwait(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + terminateIteration= false; + return true; + } + else + { + terminateIteration= false; + return false; + } + } + } + } + + internal sealed class SkipWhileIntAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileIntAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipWhileIntAwait(source, predicate, cancellationToken); + } + + class _SkipWhileIntAwait : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + int index; + + public _SkipWhileIntAwait(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent, checked(index++)); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration= false; + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + internal sealed class SkipWhileAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipWhileAwaitWithCancellation(source, predicate, cancellationToken); + } + + class _SkipWhileAwaitWithCancellation : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public _SkipWhileAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration= false; + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + internal sealed class SkipWhileIntAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _SkipWhileIntAwaitWithCancellation(source, predicate, cancellationToken); + } + + class _SkipWhileIntAwaitWithCancellation : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + int index; + + public _SkipWhileIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent, checked(index++), cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration= false; + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipWhile.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipWhile.cs.meta new file mode 100644 index 00000000..f2b210a9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/SkipWhile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b74b9fe361bf7148b51a29c8b2561e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Subscribe.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Subscribe.cs new file mode 100644 index 00000000..0785bc28 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Subscribe.cs @@ -0,0 +1,536 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; +using Subscribes = Cysharp.Threading.Tasks.Linq.Subscribe; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + // OnNext + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Action action) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, action, Subscribes.NopError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Func action) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, action, Subscribes.NopError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Func action) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, action, Subscribes.NopError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + Subscribes.SubscribeCore(source, action, Subscribes.NopError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + Subscribes.SubscribeCore(source, action, Subscribes.NopError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + Subscribes.SubscribeCore(source, action, Subscribes.NopError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static IDisposable SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static void SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static IDisposable SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static void SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + // OnNext, OnError + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Action onNext, Action onError) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, onNext, onError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Func onNext, Action onError) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, onNext, onError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Action onNext, Action onError, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + Subscribes.SubscribeCore(source, onNext, onError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Func onNext, Action onError, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + Subscribes.SubscribeCore(source, onNext, onError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static IDisposable SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onError) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeAwaitCore(source, onNext, onError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static void SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onError, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + Subscribes.SubscribeAwaitCore(source, onNext, onError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + public static IDisposable SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onError) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeAwaitCore(source, onNext, onError, Subscribes.NopCompleted, cts.Token).Forget(); + return cts; + } + + public static void SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onError, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onError, nameof(onError)); + + Subscribes.SubscribeAwaitCore(source, onNext, onError, Subscribes.NopCompleted, cancellationToken).Forget(); + } + + // OnNext, OnCompleted + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Action onNext, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, onNext, Subscribes.NopError, onCompleted, cts.Token).Forget(); + return cts; + } + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, Func onNext, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, onNext, Subscribes.NopError, onCompleted, cts.Token).Forget(); + return cts; + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Action onNext, Action onCompleted, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + Subscribes.SubscribeCore(source, onNext, Subscribes.NopError, onCompleted, cancellationToken).Forget(); + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, Func onNext, Action onCompleted, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + Subscribes.SubscribeCore(source, onNext, Subscribes.NopError, onCompleted, cancellationToken).Forget(); + } + + public static IDisposable SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, onCompleted, cts.Token).Forget(); + return cts; + } + + public static void SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onCompleted, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, onCompleted, cancellationToken).Forget(); + } + + public static IDisposable SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, onCompleted, cts.Token).Forget(); + return cts; + } + + public static void SubscribeAwait(this IUniTaskAsyncEnumerable source, Func onNext, Action onCompleted, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(onNext, nameof(onNext)); + Error.ThrowArgumentNullException(onCompleted, nameof(onCompleted)); + + Subscribes.SubscribeAwaitCore(source, onNext, Subscribes.NopError, onCompleted, cancellationToken).Forget(); + } + + // IObserver + + public static IDisposable Subscribe(this IUniTaskAsyncEnumerable source, IObserver observer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(observer, nameof(observer)); + + var cts = new CancellationTokenDisposable(); + Subscribes.SubscribeCore(source, observer, cts.Token).Forget(); + return cts; + } + + public static void Subscribe(this IUniTaskAsyncEnumerable source, IObserver observer, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(observer, nameof(observer)); + + Subscribes.SubscribeCore(source, observer, cancellationToken).Forget(); + } + } + + internal sealed class CancellationTokenDisposable : IDisposable + { + readonly CancellationTokenSource cts = new CancellationTokenSource(); + + public CancellationToken Token => cts.Token; + + public void Dispose() + { + if (!cts.IsCancellationRequested) + { + cts.Cancel(); + } + } + } + + internal static class Subscribe + { + public static readonly Action NopError = _ => { }; + public static readonly Action NopCompleted = () => { }; + + public static async UniTaskVoid SubscribeCore(IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + try + { + onNext(e.Current); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + onCompleted(); + } + catch (Exception ex) + { + if (onError == NopError) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + return; + } + + if (ex is OperationCanceledException) return; + + onError(ex); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTaskVoid SubscribeCore(IUniTaskAsyncEnumerable source, Func onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + try + { + onNext(e.Current).Forget(); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + onCompleted(); + } + catch (Exception ex) + { + if (onError == NopError) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + return; + } + + if (ex is OperationCanceledException) return; + + onError(ex); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTaskVoid SubscribeCore(IUniTaskAsyncEnumerable source, Func onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + try + { + onNext(e.Current, cancellationToken).Forget(); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + onCompleted(); + } + catch (Exception ex) + { + if (onError == NopError) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + return; + } + + if (ex is OperationCanceledException) return; + + onError(ex); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTaskVoid SubscribeCore(IUniTaskAsyncEnumerable source, IObserver observer, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + try + { + observer.OnNext(e.Current); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + observer.OnCompleted(); + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + observer.OnError(ex); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTaskVoid SubscribeAwaitCore(IUniTaskAsyncEnumerable source, Func onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + try + { + await onNext(e.Current); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + onCompleted(); + } + catch (Exception ex) + { + if (onError == NopError) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + return; + } + + if (ex is OperationCanceledException) return; + + onError(ex); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTaskVoid SubscribeAwaitCore(IUniTaskAsyncEnumerable source, Func onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + try + { + await onNext(e.Current, cancellationToken); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + onCompleted(); + } + catch (Exception ex) + { + if (onError == NopError) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + return; + } + + if (ex is OperationCanceledException) return; + + onError(ex); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Subscribe.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Subscribe.cs.meta new file mode 100644 index 00000000..ea835671 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Subscribe.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 263479eb04c189741931fc0e2f615c2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Sum.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Sum.cs new file mode 100644 index 00000000..1101cd7f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Sum.cs @@ -0,0 +1,1244 @@ +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.SumAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.SumAwaitWithCancellationAsync(source, selector, cancellationToken); + } + + } + + internal static class Sum + { + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask SumAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Sum.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Sum.cs.meta new file mode 100644 index 00000000..5331e349 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Sum.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4149754066a21a341be58c04357061f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Take.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Take.cs new file mode 100644 index 00000000..6cd4eda6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Take.cs @@ -0,0 +1,124 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Take(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Take(source, count); + } + } + + internal sealed class Take : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public Take(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Take(source, count, cancellationToken); + } + + sealed class _Take : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + int index; + + public _Take(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + if (checked(index) >= count) + { + return CompletedTasks.False; + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_Take)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.index++; + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Take.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Take.cs.meta new file mode 100644 index 00000000..1cc91ab0 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Take.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42f02cb84e5875b488304755d0e1383d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeLast.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeLast.cs new file mode 100644 index 00000000..ca0084e9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeLast.cs @@ -0,0 +1,175 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable TakeLast(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + // non take. + if (count <= 0) + { + return Empty(); + } + + return new TakeLast(source, count); + } + } + + internal sealed class TakeLast : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public TakeLast(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeLast(source, count, cancellationToken); + } + + sealed class _TakeLast : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Queue queue; + + bool iterateCompleted; + bool continueNext; + + public _TakeLast(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + queue = new Queue(); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + if (iterateCompleted) + { + if (queue.Count > 0) + { + Current = queue.Dequeue(); + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + + return; + } + + try + { + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (_TakeLast)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.queue.Count < self.count) + { + self.queue.Enqueue(self.enumerator.Current); + + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + else + { + self.queue.Dequeue(); + self.queue.Enqueue(self.enumerator.Current); + + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.iterateCompleted = true; + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeLast.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeLast.cs.meta new file mode 100644 index 00000000..d80037f4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeLast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 510aa9fd35b45fc40bcdb7e59f01fd1b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntil.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntil.cs new file mode 100644 index 00000000..25371ad9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntil.cs @@ -0,0 +1,190 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable TakeUntil(this IUniTaskAsyncEnumerable source, UniTask other) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new TakeUntil(source, other, null); + } + + public static IUniTaskAsyncEnumerable TakeUntil(this IUniTaskAsyncEnumerable source, Func other) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(other)); + + return new TakeUntil(source, default, other); + } + } + + internal sealed class TakeUntil : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly UniTask other; + readonly Func other2; + + public TakeUntil(IUniTaskAsyncEnumerable source, UniTask other, Func other2) + { + this.source = source; + this.other = other; + this.other2 = other2; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + if (other2 != null) + { + return new _TakeUntil(source, this.other2(cancellationToken), cancellationToken); + } + else + { + return new _TakeUntil(source, this.other, cancellationToken); + } + } + + sealed class _TakeUntil : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action CancelDelegate1 = OnCanceled1; + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken1; + CancellationTokenRegistration cancellationTokenRegistration1; + + bool completed; + Exception exception; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public _TakeUntil(IUniTaskAsyncEnumerable source, UniTask other, CancellationToken cancellationToken1) + { + this.source = source; + this.cancellationToken1 = cancellationToken1; + + if (cancellationToken1.CanBeCanceled) + { + this.cancellationTokenRegistration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(CancelDelegate1, this); + } + + TaskTracker.TrackActiveTask(this, 3); + + RunOther(other).Forget(); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (completed) + { + return CompletedTasks.False; + } + + if (exception != null) + { + return UniTask.FromException(exception); + } + + if (cancellationToken1.IsCancellationRequested) + { + return UniTask.FromCanceled(cancellationToken1); + } + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken1); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_TakeUntil)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.exception != null) + { + self.completionSource.TrySetException(self.exception); + } + else if (self.cancellationToken1.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken1); + } + else + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + async UniTaskVoid RunOther(UniTask other) + { + try + { + await other; + completed = true; + completionSource.TrySetResult(false); + } + catch (Exception ex) + { + exception = ex; + completionSource.TrySetException(ex); + } + } + + static void OnCanceled1(object state) + { + var self = (_TakeUntil)state; + self.completionSource.TrySetCanceled(self.cancellationToken1); + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + cancellationTokenRegistration1.Dispose(); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntil.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntil.cs.meta new file mode 100644 index 00000000..44cf63e1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 12bda324162f15349afefc2c152ac07f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntilCanceled.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntilCanceled.cs new file mode 100644 index 00000000..67ee3c8c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntilCanceled.cs @@ -0,0 +1,164 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable TakeUntilCanceled(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new TakeUntilCanceled(source, cancellationToken); + } + } + + internal sealed class TakeUntilCanceled : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly CancellationToken cancellationToken; + + public TakeUntilCanceled(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeUntilCanceled(source, this.cancellationToken, cancellationToken); + } + + sealed class _TakeUntilCanceled : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action CancelDelegate1 = OnCanceled1; + static readonly Action CancelDelegate2 = OnCanceled2; + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken1; + CancellationToken cancellationToken2; + CancellationTokenRegistration cancellationTokenRegistration1; + CancellationTokenRegistration cancellationTokenRegistration2; + + bool isCanceled; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public _TakeUntilCanceled(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken1, CancellationToken cancellationToken2) + { + this.source = source; + this.cancellationToken1 = cancellationToken1; + this.cancellationToken2 = cancellationToken2; + + if (cancellationToken1.CanBeCanceled) + { + this.cancellationTokenRegistration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(CancelDelegate1, this); + } + + if (cancellationToken1 != cancellationToken2 && cancellationToken2.CanBeCanceled) + { + this.cancellationTokenRegistration2 = cancellationToken2.RegisterWithoutCaptureExecutionContext(CancelDelegate2, this); + } + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (cancellationToken1.IsCancellationRequested) isCanceled = true; + if (cancellationToken2.IsCancellationRequested) isCanceled = true; + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken2); // use only AsyncEnumerator provided token. + } + + if (isCanceled) return CompletedTasks.False; + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (_TakeUntilCanceled)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.isCanceled) + { + self.completionSource.TrySetResult(false); + } + else + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void OnCanceled1(object state) + { + var self = (_TakeUntilCanceled)state; + if (!self.isCanceled) + { + self.cancellationTokenRegistration2.Dispose(); + self.completionSource.TrySetResult(false); + } + } + + static void OnCanceled2(object state) + { + var self = (_TakeUntilCanceled)state; + if (!self.isCanceled) + { + self.cancellationTokenRegistration1.Dispose(); + self.completionSource.TrySetResult(false); + } + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + cancellationTokenRegistration1.Dispose(); + cancellationTokenRegistration2.Dispose(); + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntilCanceled.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntilCanceled.cs.meta new file mode 100644 index 00000000..4a89be54 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeUntilCanceled.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e82f498cf3a1df04cbf646773fc11319 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeWhile.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeWhile.cs new file mode 100644 index 00000000..6239c776 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeWhile.cs @@ -0,0 +1,342 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable TakeWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhile(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileIntAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileAwaitWithCancellation(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileIntAwaitWithCancellation(source, predicate); + } + } + + internal sealed class TakeWhile : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public TakeWhile(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeWhile(source, predicate, cancellationToken); + } + + class _TakeWhile : AsyncEnumeratorBase + { + Func predicate; + + public _TakeWhile(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate(SourceCurrent)) + { + Current = SourceCurrent; + result = true; + return true; + } + } + + result = false; + return true; + } + } + } + + internal sealed class TakeWhileInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public TakeWhileInt(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeWhileInt(source, predicate, cancellationToken); + } + + class _TakeWhileInt : AsyncEnumeratorBase + { + readonly Func predicate; + int index; + + public _TakeWhileInt(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate(SourceCurrent, checked(index++))) + { + Current = SourceCurrent; + result = true; + return true; + } + } + + result = false; + return true; + } + } + } + + internal sealed class TakeWhileAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeWhileAwait(source, predicate, cancellationToken); + } + + class _TakeWhileAwait : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public _TakeWhileAwait(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } + + internal sealed class TakeWhileIntAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileIntAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeWhileIntAwait(source, predicate, cancellationToken); + } + + class _TakeWhileIntAwait : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + int index; + + public _TakeWhileIntAwait(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, checked(index++)); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } + + internal sealed class TakeWhileAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeWhileAwaitWithCancellation(source, predicate, cancellationToken); + } + + class _TakeWhileAwaitWithCancellation : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public _TakeWhileAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } + + internal sealed class TakeWhileIntAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TakeWhileIntAwaitWithCancellation(source, predicate, cancellationToken); + } + + class _TakeWhileIntAwaitWithCancellation : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + int index; + + public _TakeWhileIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, checked(index++), cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeWhile.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeWhile.cs.meta new file mode 100644 index 00000000..f2173d59 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/TakeWhile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bca55adabcc4b3141b50b8b09634f764 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Throw.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Throw.cs new file mode 100644 index 00000000..b6994c46 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Throw.cs @@ -0,0 +1,54 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Throw(Exception exception) + { + return new Throw(exception); + } + } + + internal class Throw : IUniTaskAsyncEnumerable + { + readonly Exception exception; + + public Throw(Exception exception) + { + this.exception = exception; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Throw(exception, cancellationToken); + } + + class _Throw : IUniTaskAsyncEnumerator + { + readonly Exception exception; + CancellationToken cancellationToken; + + public _Throw(Exception exception, CancellationToken cancellationToken) + { + this.exception = exception; + this.cancellationToken = cancellationToken; + } + + public TValue Current => default; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + return UniTask.FromException(exception); + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Throw.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Throw.cs.meta new file mode 100644 index 00000000..c768ef1e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Throw.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d05a7d4f4161e549b4789e1022baae8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToArray.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToArray.cs new file mode 100644 index 00000000..35549681 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToArray.cs @@ -0,0 +1,60 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ToArrayAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Cysharp.Threading.Tasks.Linq.ToArray.ToArrayAsync(source, cancellationToken); + } + } + + internal static class ToArray + { + internal static async UniTask ToArrayAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + TSource[] result = default; + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + result = Array.Empty(); + } + else + { + result = new TSource[i]; + Array.Copy(array, result, i); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + + return result; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToArray.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToArray.cs.meta new file mode 100644 index 00000000..679d61c9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToArray.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: debb010bbb1622e43b94fe70ec0133dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToDictionary.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToDictionary.cs new file mode 100644 index 00000000..083ace0c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToDictionary.cs @@ -0,0 +1,278 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToDictionary.ToDictionaryAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.ToDictionaryAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToDictionary.ToDictionaryAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.ToDictionaryAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToDictionary.ToDictionaryAwaitAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.ToDictionaryAwaitAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToDictionary.ToDictionaryAwaitAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.ToDictionaryAwaitAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToDictionary.ToDictionaryAwaitWithCancellationAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.ToDictionaryAwaitWithCancellationAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToDictionary.ToDictionaryAwaitWithCancellationAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.ToDictionaryAwaitWithCancellationAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + } + + internal static class ToDictionary + { + internal static async UniTask> ToDictionaryAsync(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = keySelector(v); + dict.Add(key, v); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + internal static async UniTask> ToDictionaryAsync(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = keySelector(v); + var value = elementSelector(v); + dict.Add(key, value); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + // with await + + internal static async UniTask> ToDictionaryAwaitAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v); + dict.Add(key, v); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + internal static async UniTask> ToDictionaryAwaitAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v); + var value = await elementSelector(v); + dict.Add(key, value); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + // with cancellation + + internal static async UniTask> ToDictionaryAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v, cancellationToken); + dict.Add(key, v); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + internal static async UniTask> ToDictionaryAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v, cancellationToken); + var value = await elementSelector(v, cancellationToken); + dict.Add(key, value); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToDictionary.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToDictionary.cs.meta new file mode 100644 index 00000000..4deed194 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03b109b1fe1f2df46aa56ffb26747654 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToHashSet.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToHashSet.cs new file mode 100644 index 00000000..d058cb1d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToHashSet.cs @@ -0,0 +1,50 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToHashSetAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Cysharp.Threading.Tasks.Linq.ToHashSet.ToHashSetAsync(source, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToHashSetAsync(this IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return Cysharp.Threading.Tasks.Linq.ToHashSet.ToHashSetAsync(source, comparer, cancellationToken); + } + } + + internal static class ToHashSet + { + internal static async UniTask> ToHashSetAsync(IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var set = new HashSet(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + set.Add(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return set; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToHashSet.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToHashSet.cs.meta new file mode 100644 index 00000000..8d3c4af2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToHashSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a3e552113af96e4986805ec3c4fc80a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToList.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToList.cs new file mode 100644 index 00000000..e6fa35e1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToList.cs @@ -0,0 +1,42 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToListAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Cysharp.Threading.Tasks.Linq.ToList.ToListAsync(source, cancellationToken); + } + } + + internal static class ToList + { + internal static async UniTask> ToListAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var list = new List(); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + list.Add(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return list; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToList.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToList.cs.meta new file mode 100644 index 00000000..4f093738 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3859c1b31e81d9b44b282e7d97e11635 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToLookup.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToLookup.cs new file mode 100644 index 00000000..015c1c07 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToLookup.cs @@ -0,0 +1,554 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToLookup.ToLookupAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.ToLookupAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToLookup.ToLookupAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.ToLookupAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToLookup.ToLookupAwaitAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.ToLookupAwaitAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToLookup.ToLookupAwaitAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.ToLookupAwaitAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToLookup.ToLookupAwaitWithCancellationAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.ToLookupAwaitWithCancellationAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToLookup.ToLookupAwaitWithCancellationAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.ToLookupAwaitWithCancellationAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + } + + internal static class ToLookup + { + internal static async UniTask> ToLookupAsync(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return Lookup.Create(new ArraySegment(array, 0, i), keySelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask> ToLookupAsync(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return Lookup.Create(new ArraySegment(array, 0, i), keySelector, elementSelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + + // with await + + internal static async UniTask> ToLookupAwaitAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask> ToLookupAwaitAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, elementSelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // with cancellation + + internal static async UniTask> ToLookupAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, comparer, cancellationToken); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask> ToLookupAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, elementSelector, comparer, cancellationToken); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // Lookup + + class Lookup : ILookup + { + static readonly Lookup empty = new Lookup(new Dictionary>()); + + // original lookup keeps order but this impl does not(dictionary not guarantee) + readonly Dictionary> dict; + + Lookup(Dictionary> dict) + { + this.dict = dict; + } + + public static Lookup CreateEmpty() + { + return empty; + } + + public static Lookup Create(ArraySegment source, Func keySelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = keySelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(arr[i]); + } + + return new Lookup(dict); + } + + public static Lookup Create(ArraySegment source, Func keySelector, Func elementSelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = keySelector(arr[i]); + var elem = elementSelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(elem); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(arr[i]); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i]); + var elem = await elementSelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(elem); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i], cancellationToken); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(arr[i]); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i], cancellationToken); + var elem = await elementSelector(arr[i], cancellationToken); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(elem); + } + + return new Lookup(dict); + } + + public IEnumerable this[TKey key] => dict.TryGetValue(key, out var g) ? g : Enumerable.Empty(); + + public int Count => dict.Count; + + public bool Contains(TKey key) + { + return dict.ContainsKey(key); + } + + public IEnumerator> GetEnumerator() + { + return dict.Values.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return dict.Values.GetEnumerator(); + } + } + + class Grouping : IGrouping // , IUniTaskAsyncGrouping + { + readonly List elements; + + public TKey Key { get; private set; } + + public Grouping(TKey key) + { + this.Key = key; + this.elements = new List(); + } + + public void Add(TElement value) + { + elements.Add(value); + } + public IEnumerator GetEnumerator() + { + return elements.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return elements.GetEnumerator(); + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this.ToUniTaskAsyncEnumerable().GetAsyncEnumerator(cancellationToken); + } + + public override string ToString() + { + return "Key: " + Key + ", Count: " + elements.Count; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToLookup.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToLookup.cs.meta new file mode 100644 index 00000000..7dd8ecd6 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToLookup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57da22563bcd6ca4aaf256d941de5cb0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToObservable.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToObservable.cs new file mode 100644 index 00000000..4f483887 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToObservable.cs @@ -0,0 +1,97 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IObservable ToObservable(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToObservable(source); + } + } + + internal sealed class ToObservable : IObservable + { + readonly IUniTaskAsyncEnumerable source; + + public ToObservable(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IDisposable Subscribe(IObserver observer) + { + var ctd = new CancellationTokenDisposable(); + + RunAsync(source, observer, ctd.Token).Forget(); + + return ctd; + } + + static async UniTaskVoid RunAsync(IUniTaskAsyncEnumerable src, IObserver observer, CancellationToken cancellationToken) + { + // cancellationToken.IsCancellationRequested is called when Rx's Disposed. + // when disposed, finish silently. + + var e = src.GetAsyncEnumerator(cancellationToken); + try + { + bool hasNext; + + do + { + try + { + hasNext = await e.MoveNextAsync(); + } + catch (Exception ex) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + observer.OnError(ex); + return; + } + + if (hasNext) + { + observer.OnNext(e.Current); + } + else + { + observer.OnCompleted(); + return; + } + } while (!cancellationToken.IsCancellationRequested); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal sealed class CancellationTokenDisposable : IDisposable + { + readonly CancellationTokenSource cts = new CancellationTokenSource(); + + public CancellationToken Token => cts.Token; + + public void Dispose() + { + if (!cts.IsCancellationRequested) + { + cts.Cancel(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToObservable.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToObservable.cs.meta new file mode 100644 index 00000000..44d917e3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToObservable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4f6f48a532188e4c80b7ebe69aea3a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToUniTaskAsyncEnumerable.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToUniTaskAsyncEnumerable.cs new file mode 100644 index 00000000..02523c6f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToUniTaskAsyncEnumerable.cs @@ -0,0 +1,1115 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.ExceptionServices; +using System.Threading; +using System.Threading.Tasks; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this IEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToUniTaskAsyncEnumerable(source); + } + + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this Task source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToUniTaskAsyncEnumerableTask(source); + } + + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this UniTask source) + { + return new ToUniTaskAsyncEnumerableUniTask(source); + } + + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this IObservable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToUniTaskAsyncEnumerableObservable(source); + } + } + + internal class ToUniTaskAsyncEnumerable : IUniTaskAsyncEnumerable + { + readonly IEnumerable source; + + public ToUniTaskAsyncEnumerable(IEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _ToUniTaskAsyncEnumerable(source, cancellationToken); + } + + class _ToUniTaskAsyncEnumerable : IUniTaskAsyncEnumerator + { + readonly IEnumerable source; + CancellationToken cancellationToken; + + IEnumerator enumerator; + + public _ToUniTaskAsyncEnumerable(IEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public T Current => enumerator.Current; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetEnumerator(); + } + + if (enumerator.MoveNext()) + { + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + enumerator.Dispose(); + return default; + } + } + } + + internal class ToUniTaskAsyncEnumerableTask : IUniTaskAsyncEnumerable + { + readonly Task source; + + public ToUniTaskAsyncEnumerableTask(Task source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _ToUniTaskAsyncEnumerableTask(source, cancellationToken); + } + + class _ToUniTaskAsyncEnumerableTask : IUniTaskAsyncEnumerator + { + readonly Task source; + CancellationToken cancellationToken; + + T current; + bool called; + + public _ToUniTaskAsyncEnumerableTask(Task source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + + this.called = false; + } + + public T Current => current; + + public async UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (called) + { + return false; + } + called = true; + + current = await source; + return true; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } + + internal class ToUniTaskAsyncEnumerableUniTask : IUniTaskAsyncEnumerable + { + readonly UniTask source; + + public ToUniTaskAsyncEnumerableUniTask(UniTask source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _ToUniTaskAsyncEnumerableUniTask(source, cancellationToken); + } + + class _ToUniTaskAsyncEnumerableUniTask : IUniTaskAsyncEnumerator + { + readonly UniTask source; + CancellationToken cancellationToken; + + T current; + bool called; + + public _ToUniTaskAsyncEnumerableUniTask(UniTask source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + + this.called = false; + } + + public T Current => current; + + public async UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (called) + { + return false; + } + called = true; + + current = await source; + return true; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } + + internal class ToUniTaskAsyncEnumerableObservable : IUniTaskAsyncEnumerable + { + readonly IObservable source; + + public ToUniTaskAsyncEnumerableObservable(IObservable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _ToUniTaskAsyncEnumerableObservable(source, cancellationToken); + } + + class _ToUniTaskAsyncEnumerableObservable : MoveNextSource, IUniTaskAsyncEnumerator, IObserver + { + static readonly Action OnCanceledDelegate = OnCanceled; + + readonly IObservable source; + CancellationToken cancellationToken; + + + bool useCachedCurrent; + T current; + bool subscribeCompleted; + readonly Queue queuedResult; + Exception error; + IDisposable subscription; + CancellationTokenRegistration cancellationTokenRegistration; + + public _ToUniTaskAsyncEnumerableObservable(IObservable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + this.queuedResult = new Queue(); + + if (cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(OnCanceledDelegate, this); + } + } + + public T Current + { + get + { + if (useCachedCurrent) + { + return current; + } + + lock (queuedResult) + { + if (queuedResult.Count != 0) + { + current = queuedResult.Dequeue(); + useCachedCurrent = true; + return current; + } + else + { + return default; // undefined. + } + } + } + } + + public UniTask MoveNextAsync() + { + lock (queuedResult) + { + useCachedCurrent = false; + + if (cancellationToken.IsCancellationRequested) + { + return UniTask.FromCanceled(cancellationToken); + } + + if (subscription == null) + { + subscription = source.Subscribe(this); + } + + if (error != null) + { + return UniTask.FromException(error); + } + + if (queuedResult.Count != 0) + { + return CompletedTasks.True; + } + + if (subscribeCompleted) + { + return CompletedTasks.False; + } + + completionSource.Reset(); + return new UniTask(this, completionSource.Version); + } + } + + public UniTask DisposeAsync() + { + subscription.Dispose(); + cancellationTokenRegistration.Dispose(); + completionSource.Reset(); + return default; + } + + public void OnCompleted() + { + lock (queuedResult) + { + subscribeCompleted = true; + completionSource.TrySetResult(false); + } + } + + public void OnError(Exception error) + { + lock (queuedResult) + { + this.error = error; + completionSource.TrySetException(error); + } + } + + public void OnNext(T value) + { + lock (queuedResult) + { + queuedResult.Enqueue(value); + completionSource.TrySetResult(true); // include callback execution, too long lock? + } + } + + static void OnCanceled(object state) + { + var self = (_ToUniTaskAsyncEnumerableObservable)state; + lock (self.queuedResult) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + } + } + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToUniTaskAsyncEnumerable.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToUniTaskAsyncEnumerable.cs.meta new file mode 100644 index 00000000..45fd3b08 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/ToUniTaskAsyncEnumerable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d7192de2a0581ec4db62962cc1404af5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UniTask.Linq.asmdef b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UniTask.Linq.asmdef new file mode 100644 index 00000000..db84553b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UniTask.Linq.asmdef @@ -0,0 +1,15 @@ +{ + "name": "UniTask.Linq", + "references": [ + "UniTask" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UniTask.Linq.asmdef.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UniTask.Linq.asmdef.meta new file mode 100644 index 00000000..1c85d19e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UniTask.Linq.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5c01796d064528144a599661eaab93a6 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Union.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Union.cs new file mode 100644 index 00000000..2ceefab1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Union.cs @@ -0,0 +1,26 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Union(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return Union(first, second, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Union(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + // improv without combinate? + return first.Concat(second).Distinct(comparer); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Union.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Union.cs.meta new file mode 100644 index 00000000..1d9c7adb --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Union.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae57a55bdeba98b4f8ff234d98d7dd76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions.meta new file mode 100644 index 00000000..7f67c569 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 54d23212553c3bb43819b90eee250ff1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryUpdate.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryUpdate.cs new file mode 100644 index 00000000..8f091100 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryUpdate.cs @@ -0,0 +1,100 @@ +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable EveryUpdate(PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool cancelImmediately = false) + { + return new EveryUpdate(updateTiming, cancelImmediately); + } + } + + internal class EveryUpdate : IUniTaskAsyncEnumerable + { + readonly PlayerLoopTiming updateTiming; + readonly bool cancelImmediately; + + public EveryUpdate(PlayerLoopTiming updateTiming, bool cancelImmediately) + { + this.updateTiming = updateTiming; + this.cancelImmediately = cancelImmediately; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _EveryUpdate(updateTiming, cancellationToken, cancelImmediately); + } + + class _EveryUpdate : MoveNextSource, IUniTaskAsyncEnumerator, IPlayerLoopItem + { + readonly PlayerLoopTiming updateTiming; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + + bool disposed; + + public _EveryUpdate(PlayerLoopTiming updateTiming, CancellationToken cancellationToken, bool cancelImmediately) + { + this.updateTiming = updateTiming; + this.cancellationToken = cancellationToken; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (_EveryUpdate)state; + source.completionSource.TrySetCanceled(source.cancellationToken); + }, this); + } + + TaskTracker.TrackActiveTask(this, 2); + PlayerLoopHelper.AddAction(updateTiming, this); + } + + public AsyncUnit Current => default; + + public UniTask MoveNextAsync() + { + if (disposed) return CompletedTasks.False; + + completionSource.Reset(); + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + } + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!disposed) + { + cancellationTokenRegistration.Dispose(); + disposed = true; + TaskTracker.RemoveTracking(this); + } + return default; + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return false; + } + + if (disposed) + { + completionSource.TrySetResult(false); + return false; + } + + completionSource.TrySetResult(true); + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryUpdate.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryUpdate.cs.meta new file mode 100644 index 00000000..6336e0e3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryUpdate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 00520eb52e49b5b4e8d9870d6ff1aced +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryValueChanged.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryValueChanged.cs new file mode 100644 index 00000000..ef5739c7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryValueChanged.cs @@ -0,0 +1,292 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable EveryValueChanged(TTarget target, Func propertySelector, PlayerLoopTiming monitorTiming = PlayerLoopTiming.Update, IEqualityComparer equalityComparer = null, bool cancelImmediately = false) + where TTarget : class + { + var unityObject = target as UnityEngine.Object; + var isUnityObject = target is UnityEngine.Object; // don't use (unityObject == null) + + if (isUnityObject) + { + return new EveryValueChangedUnityObject(target, propertySelector, equalityComparer ?? UnityEqualityComparer.GetDefault(), monitorTiming, cancelImmediately); + } + else + { + return new EveryValueChangedStandardObject(target, propertySelector, equalityComparer ?? UnityEqualityComparer.GetDefault(), monitorTiming, cancelImmediately); + } + } + } + + internal sealed class EveryValueChangedUnityObject : IUniTaskAsyncEnumerable + { + readonly TTarget target; + readonly Func propertySelector; + readonly IEqualityComparer equalityComparer; + readonly PlayerLoopTiming monitorTiming; + readonly bool cancelImmediately; + + public EveryValueChangedUnityObject(TTarget target, Func propertySelector, IEqualityComparer equalityComparer, PlayerLoopTiming monitorTiming, bool cancelImmediately) + { + this.target = target; + this.propertySelector = propertySelector; + this.equalityComparer = equalityComparer; + this.monitorTiming = monitorTiming; + this.cancelImmediately = cancelImmediately; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _EveryValueChanged(target, propertySelector, equalityComparer, monitorTiming, cancellationToken, cancelImmediately); + } + + sealed class _EveryValueChanged : MoveNextSource, IUniTaskAsyncEnumerator, IPlayerLoopItem + { + readonly TTarget target; + readonly UnityEngine.Object targetAsUnityObject; + readonly IEqualityComparer equalityComparer; + readonly Func propertySelector; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + + bool first; + TProperty currentValue; + bool disposed; + + public _EveryValueChanged(TTarget target, Func propertySelector, IEqualityComparer equalityComparer, PlayerLoopTiming monitorTiming, CancellationToken cancellationToken, bool cancelImmediately) + { + this.target = target; + this.targetAsUnityObject = target as UnityEngine.Object; + this.propertySelector = propertySelector; + this.equalityComparer = equalityComparer; + this.cancellationToken = cancellationToken; + this.first = true; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (_EveryValueChanged)state; + source.completionSource.TrySetCanceled(source.cancellationToken); + }, this); + } + + TaskTracker.TrackActiveTask(this, 2); + PlayerLoopHelper.AddAction(monitorTiming, this); + } + + public TProperty Current => currentValue; + + public UniTask MoveNextAsync() + { + if (disposed) return CompletedTasks.False; + + completionSource.Reset(); + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return new UniTask(this, completionSource.Version); + } + + if (first) + { + first = false; + if (targetAsUnityObject == null) + { + return CompletedTasks.False; + } + this.currentValue = propertySelector(target); + return CompletedTasks.True; + } + + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!disposed) + { + cancellationTokenRegistration.Dispose(); + disposed = true; + TaskTracker.RemoveTracking(this); + } + return default; + } + + public bool MoveNext() + { + if (disposed || targetAsUnityObject == null) + { + completionSource.TrySetResult(false); + DisposeAsync().Forget(); + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return false; + } + TProperty nextValue = default(TProperty); + try + { + nextValue = propertySelector(target); + if (equalityComparer.Equals(currentValue, nextValue)) + { + return true; + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + DisposeAsync().Forget(); + return false; + } + + currentValue = nextValue; + completionSource.TrySetResult(true); + return true; + } + } + } + + internal sealed class EveryValueChangedStandardObject : IUniTaskAsyncEnumerable + where TTarget : class + { + readonly WeakReference target; + readonly Func propertySelector; + readonly IEqualityComparer equalityComparer; + readonly PlayerLoopTiming monitorTiming; + readonly bool cancelImmediately; + + public EveryValueChangedStandardObject(TTarget target, Func propertySelector, IEqualityComparer equalityComparer, PlayerLoopTiming monitorTiming, bool cancelImmediately) + { + this.target = new WeakReference(target, false); + this.propertySelector = propertySelector; + this.equalityComparer = equalityComparer; + this.monitorTiming = monitorTiming; + this.cancelImmediately = cancelImmediately; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _EveryValueChanged(target, propertySelector, equalityComparer, monitorTiming, cancellationToken, cancelImmediately); + } + + sealed class _EveryValueChanged : MoveNextSource, IUniTaskAsyncEnumerator, IPlayerLoopItem + { + readonly WeakReference target; + readonly IEqualityComparer equalityComparer; + readonly Func propertySelector; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + + bool first; + TProperty currentValue; + bool disposed; + + public _EveryValueChanged(WeakReference target, Func propertySelector, IEqualityComparer equalityComparer, PlayerLoopTiming monitorTiming, CancellationToken cancellationToken, bool cancelImmediately) + { + this.target = target; + this.propertySelector = propertySelector; + this.equalityComparer = equalityComparer; + this.cancellationToken = cancellationToken; + this.first = true; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (_EveryValueChanged)state; + source.completionSource.TrySetCanceled(source.cancellationToken); + }, this); + } + + TaskTracker.TrackActiveTask(this, 2); + PlayerLoopHelper.AddAction(monitorTiming, this); + } + + public TProperty Current => currentValue; + + public UniTask MoveNextAsync() + { + if (disposed) return CompletedTasks.False; + + completionSource.Reset(); + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return new UniTask(this, completionSource.Version); + } + + if (first) + { + first = false; + if (!target.TryGetTarget(out var t)) + { + return CompletedTasks.False; + } + this.currentValue = propertySelector(t); + return CompletedTasks.True; + } + + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!disposed) + { + cancellationTokenRegistration.Dispose(); + disposed = true; + TaskTracker.RemoveTracking(this); + } + return default; + } + + public bool MoveNext() + { + if (disposed || !target.TryGetTarget(out var t)) + { + completionSource.TrySetResult(false); + DisposeAsync().Forget(); + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return false; + } + + TProperty nextValue = default(TProperty); + try + { + nextValue = propertySelector(t); + if (equalityComparer.Equals(currentValue, nextValue)) + { + return true; + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + DisposeAsync().Forget(); + return false; + } + + currentValue = nextValue; + completionSource.TrySetResult(true); + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryValueChanged.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryValueChanged.cs.meta new file mode 100644 index 00000000..9d2be702 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/EveryValueChanged.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1ec39f1c41c305344854782c935ad354 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/Timer.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/Timer.cs new file mode 100644 index 00000000..b8aabf23 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/Timer.cs @@ -0,0 +1,355 @@ +using System; +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Timer(TimeSpan dueTime, PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool ignoreTimeScale = false, bool cancelImmediately = false) + { + return new Timer(dueTime, null, updateTiming, ignoreTimeScale, cancelImmediately); + } + + public static IUniTaskAsyncEnumerable Timer(TimeSpan dueTime, TimeSpan period, PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool ignoreTimeScale = false, bool cancelImmediately = false) + { + return new Timer(dueTime, period, updateTiming, ignoreTimeScale, cancelImmediately); + } + + public static IUniTaskAsyncEnumerable Interval(TimeSpan period, PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool ignoreTimeScale = false, bool cancelImmediately = false) + { + return new Timer(period, period, updateTiming, ignoreTimeScale, cancelImmediately); + } + + public static IUniTaskAsyncEnumerable TimerFrame(int dueTimeFrameCount, PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool cancelImmediately = false) + { + if (dueTimeFrameCount < 0) + { + throw new ArgumentOutOfRangeException("Delay does not allow minus delayFrameCount. dueTimeFrameCount:" + dueTimeFrameCount); + } + + return new TimerFrame(dueTimeFrameCount, null, updateTiming, cancelImmediately); + } + + public static IUniTaskAsyncEnumerable TimerFrame(int dueTimeFrameCount, int periodFrameCount, PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool cancelImmediately = false) + { + if (dueTimeFrameCount < 0) + { + throw new ArgumentOutOfRangeException("Delay does not allow minus delayFrameCount. dueTimeFrameCount:" + dueTimeFrameCount); + } + if (periodFrameCount < 0) + { + throw new ArgumentOutOfRangeException("Delay does not allow minus periodFrameCount. periodFrameCount:" + dueTimeFrameCount); + } + + return new TimerFrame(dueTimeFrameCount, periodFrameCount, updateTiming, cancelImmediately); + } + + public static IUniTaskAsyncEnumerable IntervalFrame(int intervalFrameCount, PlayerLoopTiming updateTiming = PlayerLoopTiming.Update, bool cancelImmediately = false) + { + if (intervalFrameCount < 0) + { + throw new ArgumentOutOfRangeException("Delay does not allow minus intervalFrameCount. intervalFrameCount:" + intervalFrameCount); + } + return new TimerFrame(intervalFrameCount, intervalFrameCount, updateTiming, cancelImmediately); + } + } + + internal class Timer : IUniTaskAsyncEnumerable + { + readonly PlayerLoopTiming updateTiming; + readonly TimeSpan dueTime; + readonly TimeSpan? period; + readonly bool ignoreTimeScale; + readonly bool cancelImmediately; + + public Timer(TimeSpan dueTime, TimeSpan? period, PlayerLoopTiming updateTiming, bool ignoreTimeScale, bool cancelImmediately) + { + this.updateTiming = updateTiming; + this.dueTime = dueTime; + this.period = period; + this.ignoreTimeScale = ignoreTimeScale; + this.cancelImmediately = cancelImmediately; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Timer(dueTime, period, updateTiming, ignoreTimeScale, cancellationToken, cancelImmediately); + } + + class _Timer : MoveNextSource, IUniTaskAsyncEnumerator, IPlayerLoopItem + { + readonly float dueTime; + readonly float? period; + readonly PlayerLoopTiming updateTiming; + readonly bool ignoreTimeScale; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + + int initialFrame; + float elapsed; + bool dueTimePhase; + bool completed; + bool disposed; + + public _Timer(TimeSpan dueTime, TimeSpan? period, PlayerLoopTiming updateTiming, bool ignoreTimeScale, CancellationToken cancellationToken, bool cancelImmediately) + { + this.dueTime = (float)dueTime.TotalSeconds; + this.period = (period == null) ? null : (float?)period.Value.TotalSeconds; + + if (this.dueTime <= 0) this.dueTime = 0; + if (this.period != null) + { + if (this.period <= 0) this.period = 1; + } + + this.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + this.dueTimePhase = true; + this.updateTiming = updateTiming; + this.ignoreTimeScale = ignoreTimeScale; + this.cancellationToken = cancellationToken; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (_Timer)state; + source.completionSource.TrySetCanceled(source.cancellationToken); + }, this); + } + + TaskTracker.TrackActiveTask(this, 2); + PlayerLoopHelper.AddAction(updateTiming, this); + } + + public AsyncUnit Current => default; + + public UniTask MoveNextAsync() + { + // return false instead of throw + if (disposed || completed) return CompletedTasks.False; + + // reset value here. + this.elapsed = 0; + + completionSource.Reset(); + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + } + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!disposed) + { + cancellationTokenRegistration.Dispose(); + disposed = true; + TaskTracker.RemoveTracking(this); + } + return default; + } + + public bool MoveNext() + { + if (disposed) + { + completionSource.TrySetResult(false); + return false; + } + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return false; + } + + if (dueTimePhase) + { + if (elapsed == 0) + { + // skip in initial frame. + if (initialFrame == Time.frameCount) + { + return true; + } + } + + elapsed += (ignoreTimeScale) ? UnityEngine.Time.unscaledDeltaTime : UnityEngine.Time.deltaTime; + + if (elapsed >= dueTime) + { + dueTimePhase = false; + completionSource.TrySetResult(true); + } + } + else + { + if (period == null) + { + completed = true; + completionSource.TrySetResult(false); + return false; + } + + elapsed += (ignoreTimeScale) ? UnityEngine.Time.unscaledDeltaTime : UnityEngine.Time.deltaTime; + + if (elapsed >= period) + { + completionSource.TrySetResult(true); + } + } + + return true; + } + } + } + + internal class TimerFrame : IUniTaskAsyncEnumerable + { + readonly PlayerLoopTiming updateTiming; + readonly int dueTimeFrameCount; + readonly int? periodFrameCount; + readonly bool cancelImmediately; + + public TimerFrame(int dueTimeFrameCount, int? periodFrameCount, PlayerLoopTiming updateTiming, bool cancelImmediately) + { + this.updateTiming = updateTiming; + this.dueTimeFrameCount = dueTimeFrameCount; + this.periodFrameCount = periodFrameCount; + this.cancelImmediately = cancelImmediately; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _TimerFrame(dueTimeFrameCount, periodFrameCount, updateTiming, cancellationToken, cancelImmediately); + } + + class _TimerFrame : MoveNextSource, IUniTaskAsyncEnumerator, IPlayerLoopItem + { + readonly int dueTimeFrameCount; + readonly int? periodFrameCount; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration cancellationTokenRegistration; + + int initialFrame; + int currentFrame; + bool dueTimePhase; + bool completed; + bool disposed; + + public _TimerFrame(int dueTimeFrameCount, int? periodFrameCount, PlayerLoopTiming updateTiming, CancellationToken cancellationToken, bool cancelImmediately) + { + if (dueTimeFrameCount <= 0) dueTimeFrameCount = 0; + if (periodFrameCount != null) + { + if (periodFrameCount <= 0) periodFrameCount = 1; + } + + this.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + this.dueTimePhase = true; + this.dueTimeFrameCount = dueTimeFrameCount; + this.periodFrameCount = periodFrameCount; + this.cancellationToken = cancellationToken; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (_TimerFrame)state; + source.completionSource.TrySetCanceled(source.cancellationToken); + }, this); + } + + TaskTracker.TrackActiveTask(this, 2); + PlayerLoopHelper.AddAction(updateTiming, this); + } + + public AsyncUnit Current => default; + + public UniTask MoveNextAsync() + { + if (disposed || completed) return CompletedTasks.False; + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + } + + // reset value here. + this.currentFrame = 0; + completionSource.Reset(); + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!disposed) + { + cancellationTokenRegistration.Dispose(); + disposed = true; + TaskTracker.RemoveTracking(this); + } + return default; + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + return false; + } + if (disposed) + { + completionSource.TrySetResult(false); + return false; + } + + if (dueTimePhase) + { + if (currentFrame == 0) + { + if (dueTimeFrameCount == 0) + { + dueTimePhase = false; + completionSource.TrySetResult(true); + return true; + } + + // skip in initial frame. + if (initialFrame == Time.frameCount) + { + return true; + } + } + + if (++currentFrame >= dueTimeFrameCount) + { + dueTimePhase = false; + completionSource.TrySetResult(true); + } + else + { + } + } + else + { + if (periodFrameCount == null) + { + completed = true; + completionSource.TrySetResult(false); + return false; + } + + if (++currentFrame >= periodFrameCount) + { + completionSource.TrySetResult(true); + } + } + + return true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/Timer.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/Timer.cs.meta new file mode 100644 index 00000000..aa790c52 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/UnityExtensions/Timer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 382caacde439855418709c641e4d7b04 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Where.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Where.cs new file mode 100644 index 00000000..1b5ac47f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Where.cs @@ -0,0 +1,818 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Where(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new Where(source, predicate); + } + + public static IUniTaskAsyncEnumerable Where(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereIntAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereAwaitWithCancellation(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereIntAwaitWithCancellation(source, predicate); + } + } + + internal sealed class Where : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public Where(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Where(source, predicate, cancellationToken); + } + + sealed class _Where : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Action moveNextAction; + + public _Where(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + this.source = source; + this.predicate = predicate; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = enumerator.Current; + if (predicate(Current)) + { + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + } + else + { + goto DONE; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class WhereInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public WhereInt(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Where(source, predicate, cancellationToken); + } + + sealed class _Where : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Action moveNextAction; + int index; + + public _Where(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + this.source = source; + this.predicate = predicate; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = enumerator.Current; + if (predicate(Current, checked(index++))) + { + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + } + else + { + goto DONE; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class WhereAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _WhereAwait(source, predicate, cancellationToken); + } + + sealed class _WhereAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + + public _WhereAwait(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + this.source = source; + this.predicate = predicate; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = enumerator.Current; + + awaiter2 = predicate(Current).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + if (awaiter2.GetResult()) + { + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class WhereIntAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereIntAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _WhereAwait(source, predicate, cancellationToken); + } + + sealed class _WhereAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + int index; + + public _WhereAwait(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + this.source = source; + this.predicate = predicate; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = enumerator.Current; + + awaiter2 = predicate(Current, checked(index++)).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + if (awaiter2.GetResult()) + { + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class WhereAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _WhereAwaitWithCancellation(source, predicate, cancellationToken); + } + + sealed class _WhereAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + + public _WhereAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + this.source = source; + this.predicate = predicate; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = enumerator.Current; + + awaiter2 = predicate(Current, cancellationToken).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + if (awaiter2.GetResult()) + { + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } + + internal sealed class WhereIntAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _WhereAwaitWithCancellation(source, predicate, cancellationToken); + } + + sealed class _WhereAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + readonly CancellationToken cancellationToken; + + int state = -1; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + UniTask.Awaiter awaiter2; + Action moveNextAction; + int index; + + public _WhereAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + this.source = source; + this.predicate = predicate; + this.cancellationToken = cancellationToken; + this.moveNextAction = MoveNext; + TaskTracker.TrackActiveTask(this, 3); + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + if (state == -2) return default; + + completionSource.Reset(); + MoveNext(); + return new UniTask(this, completionSource.Version); + } + + void MoveNext() + { + REPEAT: + try + { + switch (state) + { + case -1: // init + enumerator = source.GetAsyncEnumerator(cancellationToken); + goto case 0; + case 0: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + goto case 1; + } + else + { + state = 1; + awaiter.UnsafeOnCompleted(moveNextAction); + return; + } + case 1: + if (awaiter.GetResult()) + { + Current = enumerator.Current; + + awaiter2 = predicate(Current, checked(index++), cancellationToken).GetAwaiter(); + if (awaiter2.IsCompleted) + { + goto case 2; + } + else + { + state = 2; + awaiter2.UnsafeOnCompleted(moveNextAction); + return; + } + } + else + { + goto DONE; + } + case 2: + if (awaiter2.GetResult()) + { + goto CONTINUE; + } + else + { + state = 0; + goto REPEAT; + } + default: + goto DONE; + } + } + catch (Exception ex) + { + state = -2; + completionSource.TrySetException(ex); + return; + } + + DONE: + state = -2; + completionSource.TrySetResult(false); + return; + + CONTINUE: + state = 0; + completionSource.TrySetResult(true); + return; + } + + public UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + return enumerator.DisposeAsync(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Where.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Where.cs.meta new file mode 100644 index 00000000..7e503375 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Where.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d882a3238d9535e4e8ce1ad3291eb7fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Zip.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Zip.cs new file mode 100644 index 00000000..af6d5f17 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Zip.cs @@ -0,0 +1,541 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + + public static IUniTaskAsyncEnumerable<(TFirst First, TSecond Second)> Zip(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return Zip(first, second, (x, y) => (x, y)); + } + + public static IUniTaskAsyncEnumerable Zip(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func resultSelector) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new Zip(first, second, resultSelector); + } + + public static IUniTaskAsyncEnumerable ZipAwait(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> selector) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new ZipAwait(first, second, selector); + } + + public static IUniTaskAsyncEnumerable ZipAwaitWithCancellation(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> selector) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new ZipAwaitWithCancellation(first, second, selector); + } + } + + internal sealed class Zip : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func resultSelector; + + public Zip(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func resultSelector) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _Zip(first, second, resultSelector, cancellationToken); + } + + sealed class _Zip : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action firstMoveNextCoreDelegate = FirstMoveNextCore; + static readonly Action secondMoveNextCoreDelegate = SecondMoveNextCore; + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func resultSelector; + + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator firstEnumerator; + IUniTaskAsyncEnumerator secondEnumerator; + + UniTask.Awaiter firstAwaiter; + UniTask.Awaiter secondAwaiter; + + public _Zip(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func resultSelector, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + if (firstEnumerator == null) + { + firstEnumerator = first.GetAsyncEnumerator(cancellationToken); + secondEnumerator = second.GetAsyncEnumerator(cancellationToken); + } + + firstAwaiter = firstEnumerator.MoveNextAsync().GetAwaiter(); + + if (firstAwaiter.IsCompleted) + { + FirstMoveNextCore(this); + } + else + { + firstAwaiter.SourceOnCompleted(firstMoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void FirstMoveNextCore(object state) + { + var self = (_Zip)state; + + if (self.TryGetResult(self.firstAwaiter, out var result)) + { + if (result) + { + try + { + self.secondAwaiter = self.secondEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.secondAwaiter.IsCompleted) + { + SecondMoveNextCore(self); + } + else + { + self.secondAwaiter.SourceOnCompleted(secondMoveNextCoreDelegate, self); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SecondMoveNextCore(object state) + { + var self = (_Zip)state; + + if (self.TryGetResult(self.secondAwaiter, out var result)) + { + if (result) + { + try + { + self.Current = self.resultSelector(self.firstEnumerator.Current, self.secondEnumerator.Current); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(true); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (firstEnumerator != null) + { + await firstEnumerator.DisposeAsync(); + } + if (secondEnumerator != null) + { + await secondEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class ZipAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + public ZipAwait(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _ZipAwait(first, second, resultSelector, cancellationToken); + } + + sealed class _ZipAwait : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action firstMoveNextCoreDelegate = FirstMoveNextCore; + static readonly Action secondMoveNextCoreDelegate = SecondMoveNextCore; + static readonly Action resultAwaitCoreDelegate = ResultAwaitCore; + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator firstEnumerator; + IUniTaskAsyncEnumerator secondEnumerator; + + UniTask.Awaiter firstAwaiter; + UniTask.Awaiter secondAwaiter; + UniTask.Awaiter resultAwaiter; + + public _ZipAwait(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + if (firstEnumerator == null) + { + firstEnumerator = first.GetAsyncEnumerator(cancellationToken); + secondEnumerator = second.GetAsyncEnumerator(cancellationToken); + } + + firstAwaiter = firstEnumerator.MoveNextAsync().GetAwaiter(); + + if (firstAwaiter.IsCompleted) + { + FirstMoveNextCore(this); + } + else + { + firstAwaiter.SourceOnCompleted(firstMoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void FirstMoveNextCore(object state) + { + var self = (_ZipAwait)state; + + if (self.TryGetResult(self.firstAwaiter, out var result)) + { + if (result) + { + try + { + self.secondAwaiter = self.secondEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.secondAwaiter.IsCompleted) + { + SecondMoveNextCore(self); + } + else + { + self.secondAwaiter.SourceOnCompleted(secondMoveNextCoreDelegate, self); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SecondMoveNextCore(object state) + { + var self = (_ZipAwait)state; + + if (self.TryGetResult(self.secondAwaiter, out var result)) + { + if (result) + { + try + { + self.resultAwaiter = self.resultSelector(self.firstEnumerator.Current, self.secondEnumerator.Current).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultAwaitCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(resultAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void ResultAwaitCore(object state) + { + var self = (_ZipAwait)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(true); + } + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (firstEnumerator != null) + { + await firstEnumerator.DisposeAsync(); + } + if (secondEnumerator != null) + { + await secondEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class ZipAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + public ZipAwaitWithCancellation(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new _ZipAwaitWithCancellation(first, second, resultSelector, cancellationToken); + } + + sealed class _ZipAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action firstMoveNextCoreDelegate = FirstMoveNextCore; + static readonly Action secondMoveNextCoreDelegate = SecondMoveNextCore; + static readonly Action resultAwaitCoreDelegate = ResultAwaitCore; + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator firstEnumerator; + IUniTaskAsyncEnumerator secondEnumerator; + + UniTask.Awaiter firstAwaiter; + UniTask.Awaiter secondAwaiter; + UniTask.Awaiter resultAwaiter; + + public _ZipAwaitWithCancellation(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + TaskTracker.TrackActiveTask(this, 3); + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + if (firstEnumerator == null) + { + firstEnumerator = first.GetAsyncEnumerator(cancellationToken); + secondEnumerator = second.GetAsyncEnumerator(cancellationToken); + } + + firstAwaiter = firstEnumerator.MoveNextAsync().GetAwaiter(); + + if (firstAwaiter.IsCompleted) + { + FirstMoveNextCore(this); + } + else + { + firstAwaiter.SourceOnCompleted(firstMoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void FirstMoveNextCore(object state) + { + var self = (_ZipAwaitWithCancellation)state; + + if (self.TryGetResult(self.firstAwaiter, out var result)) + { + if (result) + { + try + { + self.secondAwaiter = self.secondEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.secondAwaiter.IsCompleted) + { + SecondMoveNextCore(self); + } + else + { + self.secondAwaiter.SourceOnCompleted(secondMoveNextCoreDelegate, self); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SecondMoveNextCore(object state) + { + var self = (_ZipAwaitWithCancellation)state; + + if (self.TryGetResult(self.secondAwaiter, out var result)) + { + if (result) + { + try + { + self.resultAwaiter = self.resultSelector(self.firstEnumerator.Current, self.secondEnumerator.Current, self.cancellationToken).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultAwaitCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(resultAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void ResultAwaitCore(object state) + { + var self = (_ZipAwaitWithCancellation)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(true); + } + } + } + + public async UniTask DisposeAsync() + { + TaskTracker.RemoveTracking(this); + if (firstEnumerator != null) + { + await firstEnumerator.DisposeAsync(); + } + if (secondEnumerator != null) + { + await secondEnumerator.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Zip.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Zip.cs.meta new file mode 100644 index 00000000..bf121637 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Linq/Zip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: acc1acff153e347418f0f30b1c535994 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/MoveNextSource.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/MoveNextSource.cs new file mode 100644 index 00000000..3e9ca236 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/MoveNextSource.cs @@ -0,0 +1,63 @@ +using System; + +namespace Cysharp.Threading.Tasks +{ + public abstract class MoveNextSource : IUniTaskSource + { + protected UniTaskCompletionSourceCore completionSource; + + public bool GetResult(short token) + { + return completionSource.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return completionSource.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + completionSource.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return completionSource.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + completionSource.GetResult(token); + } + + protected bool TryGetResult(UniTask.Awaiter awaiter, out T result) + { + try + { + result = awaiter.GetResult(); + return true; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + result = default; + return false; + } + } + + protected bool TryGetResult(UniTask.Awaiter awaiter) + { + try + { + awaiter.GetResult(); + return true; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return false; + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/MoveNextSource.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/MoveNextSource.cs.meta new file mode 100644 index 00000000..60a0908c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/MoveNextSource.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc4c5dc2a5f246e4f8df44cab735826c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopHelper.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopHelper.cs new file mode 100644 index 00000000..b17375e7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopHelper.cs @@ -0,0 +1,581 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Linq; +using UnityEngine; +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +#if UNITY_2019_3_OR_NEWER +using UnityEngine.LowLevel; +using PlayerLoopType = UnityEngine.PlayerLoop; +#else +using UnityEngine.Experimental.LowLevel; +using PlayerLoopType = UnityEngine.Experimental.PlayerLoop; +#endif + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace Cysharp.Threading.Tasks +{ + public static class UniTaskLoopRunners + { + public struct UniTaskLoopRunnerInitialization { }; + public struct UniTaskLoopRunnerEarlyUpdate { }; + public struct UniTaskLoopRunnerFixedUpdate { }; + public struct UniTaskLoopRunnerPreUpdate { }; + public struct UniTaskLoopRunnerUpdate { }; + public struct UniTaskLoopRunnerPreLateUpdate { }; + public struct UniTaskLoopRunnerPostLateUpdate { }; + + // Last + + public struct UniTaskLoopRunnerLastInitialization { }; + public struct UniTaskLoopRunnerLastEarlyUpdate { }; + public struct UniTaskLoopRunnerLastFixedUpdate { }; + public struct UniTaskLoopRunnerLastPreUpdate { }; + public struct UniTaskLoopRunnerLastUpdate { }; + public struct UniTaskLoopRunnerLastPreLateUpdate { }; + public struct UniTaskLoopRunnerLastPostLateUpdate { }; + + // Yield + + public struct UniTaskLoopRunnerYieldInitialization { }; + public struct UniTaskLoopRunnerYieldEarlyUpdate { }; + public struct UniTaskLoopRunnerYieldFixedUpdate { }; + public struct UniTaskLoopRunnerYieldPreUpdate { }; + public struct UniTaskLoopRunnerYieldUpdate { }; + public struct UniTaskLoopRunnerYieldPreLateUpdate { }; + public struct UniTaskLoopRunnerYieldPostLateUpdate { }; + + // Yield Last + + public struct UniTaskLoopRunnerLastYieldInitialization { }; + public struct UniTaskLoopRunnerLastYieldEarlyUpdate { }; + public struct UniTaskLoopRunnerLastYieldFixedUpdate { }; + public struct UniTaskLoopRunnerLastYieldPreUpdate { }; + public struct UniTaskLoopRunnerLastYieldUpdate { }; + public struct UniTaskLoopRunnerLastYieldPreLateUpdate { }; + public struct UniTaskLoopRunnerLastYieldPostLateUpdate { }; + +#if UNITY_2020_2_OR_NEWER + public struct UniTaskLoopRunnerTimeUpdate { }; + public struct UniTaskLoopRunnerLastTimeUpdate { }; + public struct UniTaskLoopRunnerYieldTimeUpdate { }; + public struct UniTaskLoopRunnerLastYieldTimeUpdate { }; +#endif + } + + public enum PlayerLoopTiming + { + Initialization = 0, + LastInitialization = 1, + + EarlyUpdate = 2, + LastEarlyUpdate = 3, + + FixedUpdate = 4, + LastFixedUpdate = 5, + + PreUpdate = 6, + LastPreUpdate = 7, + + Update = 8, + LastUpdate = 9, + + PreLateUpdate = 10, + LastPreLateUpdate = 11, + + PostLateUpdate = 12, + LastPostLateUpdate = 13, + +#if UNITY_2020_2_OR_NEWER + // Unity 2020.2 added TimeUpdate https://docs.unity3d.com/2020.2/Documentation/ScriptReference/PlayerLoop.TimeUpdate.html + TimeUpdate = 14, + LastTimeUpdate = 15, +#endif + } + + [Flags] + public enum InjectPlayerLoopTimings + { + /// + /// Preset: All loops(default). + /// + All = + Initialization | LastInitialization | + EarlyUpdate | LastEarlyUpdate | + FixedUpdate | LastFixedUpdate | + PreUpdate | LastPreUpdate | + Update | LastUpdate | + PreLateUpdate | LastPreLateUpdate | + PostLateUpdate | LastPostLateUpdate +#if UNITY_2020_2_OR_NEWER + | TimeUpdate | LastTimeUpdate, +#else + , +#endif + + /// + /// Preset: All without last except LastPostLateUpdate. + /// + Standard = + Initialization | + EarlyUpdate | + FixedUpdate | + PreUpdate | + Update | + PreLateUpdate | + PostLateUpdate | LastPostLateUpdate +#if UNITY_2020_2_OR_NEWER + | TimeUpdate +#endif + , + + /// + /// Preset: Minimum pattern, Update | FixedUpdate | LastPostLateUpdate + /// + Minimum = + Update | FixedUpdate | LastPostLateUpdate, + + // PlayerLoopTiming + + Initialization = 1, + LastInitialization = 2, + + EarlyUpdate = 4, + LastEarlyUpdate = 8, + + FixedUpdate = 16, + LastFixedUpdate = 32, + + PreUpdate = 64, + LastPreUpdate = 128, + + Update = 256, + LastUpdate = 512, + + PreLateUpdate = 1024, + LastPreLateUpdate = 2048, + + PostLateUpdate = 4096, + LastPostLateUpdate = 8192 + +#if UNITY_2020_2_OR_NEWER + , + // Unity 2020.2 added TimeUpdate https://docs.unity3d.com/2020.2/Documentation/ScriptReference/PlayerLoop.TimeUpdate.html + TimeUpdate = 16384, + LastTimeUpdate = 32768 +#endif + } + + public interface IPlayerLoopItem + { + bool MoveNext(); + } + + public static class PlayerLoopHelper + { + static readonly ContinuationQueue ThrowMarkerContinuationQueue = new ContinuationQueue(PlayerLoopTiming.Initialization); + static readonly PlayerLoopRunner ThrowMarkerPlayerLoopRunner = new PlayerLoopRunner(PlayerLoopTiming.Initialization); + + public static SynchronizationContext UnitySynchronizationContext => unitySynchronizationContext; + public static int MainThreadId => mainThreadId; + internal static string ApplicationDataPath => applicationDataPath; + + public static bool IsMainThread => Thread.CurrentThread.ManagedThreadId == mainThreadId; + + static int mainThreadId; + static string applicationDataPath; + static SynchronizationContext unitySynchronizationContext; + static ContinuationQueue[] yielders; + static PlayerLoopRunner[] runners; + internal static bool IsEditorApplicationQuitting { get; private set; } + static PlayerLoopSystem[] InsertRunner(PlayerLoopSystem loopSystem, + bool injectOnFirst, + Type loopRunnerYieldType, ContinuationQueue cq, + Type loopRunnerType, PlayerLoopRunner runner) + { + +#if UNITY_EDITOR + EditorApplication.playModeStateChanged += (state) => + { + if (state == PlayModeStateChange.EnteredEditMode || state == PlayModeStateChange.ExitingEditMode) + { + IsEditorApplicationQuitting = true; + // run rest action before clear. + if (runner != null) + { + runner.Run(); + runner.Clear(); + } + if (cq != null) + { + cq.Run(); + cq.Clear(); + } + IsEditorApplicationQuitting = false; + } + }; +#endif + + var yieldLoop = new PlayerLoopSystem + { + type = loopRunnerYieldType, + updateDelegate = cq.Run + }; + + var runnerLoop = new PlayerLoopSystem + { + type = loopRunnerType, + updateDelegate = runner.Run + }; + + // Remove items from previous initializations. + var source = RemoveRunner(loopSystem, loopRunnerYieldType, loopRunnerType); + var dest = new PlayerLoopSystem[source.Length + 2]; + + Array.Copy(source, 0, dest, injectOnFirst ? 2 : 0, source.Length); + if (injectOnFirst) + { + dest[0] = yieldLoop; + dest[1] = runnerLoop; + } + else + { + dest[dest.Length - 2] = yieldLoop; + dest[dest.Length - 1] = runnerLoop; + } + + return dest; + } + + static PlayerLoopSystem[] RemoveRunner(PlayerLoopSystem loopSystem, Type loopRunnerYieldType, Type loopRunnerType) + { + return loopSystem.subSystemList + .Where(ls => ls.type != loopRunnerYieldType && ls.type != loopRunnerType) + .ToArray(); + } + + static PlayerLoopSystem[] InsertUniTaskSynchronizationContext(PlayerLoopSystem loopSystem) + { + var loop = new PlayerLoopSystem + { + type = typeof(UniTaskSynchronizationContext), + updateDelegate = UniTaskSynchronizationContext.Run + }; + + // Remove items from previous initializations. + var source = loopSystem.subSystemList + .Where(ls => ls.type != typeof(UniTaskSynchronizationContext)) + .ToArray(); + + var dest = new System.Collections.Generic.List(source); + + var index = dest.FindIndex(x => x.type.Name == "ScriptRunDelayedTasks"); + if (index == -1) + { + index = dest.FindIndex(x => x.type.Name == "UniTaskLoopRunnerUpdate"); + } + + dest.Insert(index + 1, loop); + + return dest.ToArray(); + } + +#if UNITY_2020_1_OR_NEWER + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] +#else + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] +#endif + static void Init() + { + // capture default(unity) sync-context. + unitySynchronizationContext = SynchronizationContext.Current; + mainThreadId = Thread.CurrentThread.ManagedThreadId; + try + { + applicationDataPath = Application.dataPath; + } + catch { } + +#if UNITY_EDITOR && UNITY_2019_3_OR_NEWER + // When domain reload is disabled, re-initialization is required when entering play mode; + // otherwise, pending tasks will leak between play mode sessions. + var domainReloadDisabled = UnityEditor.EditorSettings.enterPlayModeOptionsEnabled && + UnityEditor.EditorSettings.enterPlayModeOptions.HasFlag(UnityEditor.EnterPlayModeOptions.DisableDomainReload); + if (!domainReloadDisabled && runners != null) return; +#else + if (runners != null) return; // already initialized +#endif + + var playerLoop = +#if UNITY_2019_3_OR_NEWER + PlayerLoop.GetCurrentPlayerLoop(); +#else + PlayerLoop.GetDefaultPlayerLoop(); +#endif + + Initialize(ref playerLoop); + } + + +#if UNITY_EDITOR + + [InitializeOnLoadMethod] + static void InitOnEditor() + { + // Execute the play mode init method + Init(); + + // register an Editor update delegate, used to forcing playerLoop update + EditorApplication.update += ForceEditorPlayerLoopUpdate; + } + + private static void ForceEditorPlayerLoopUpdate() + { + if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling || EditorApplication.isUpdating) + { + // Not in Edit mode, don't interfere + return; + } + + // EditorApplication.QueuePlayerLoopUpdate causes performance issue, don't call directly. + // EditorApplication.QueuePlayerLoopUpdate(); + + if (yielders != null) + { + foreach (var item in yielders) + { + if (item != null) item.Run(); + } + } + + if (runners != null) + { + foreach (var item in runners) + { + if (item != null) item.Run(); + } + } + + UniTaskSynchronizationContext.Run(); + } + +#endif + + private static int FindLoopSystemIndex(PlayerLoopSystem[] playerLoopList, Type systemType) + { + for (int i = 0; i < playerLoopList.Length; i++) + { + if (playerLoopList[i].type == systemType) + { + return i; + } + } + + throw new Exception("Target PlayerLoopSystem does not found. Type:" + systemType.FullName); + } + + static void InsertLoop(PlayerLoopSystem[] copyList, InjectPlayerLoopTimings injectTimings, Type loopType, InjectPlayerLoopTimings targetTimings, + int index, bool injectOnFirst, Type loopRunnerYieldType, Type loopRunnerType, PlayerLoopTiming playerLoopTiming) + { + var i = FindLoopSystemIndex(copyList, loopType); + if ((injectTimings & targetTimings) == targetTimings) + { + copyList[i].subSystemList = InsertRunner(copyList[i], injectOnFirst, + loopRunnerYieldType, yielders[index] = new ContinuationQueue(playerLoopTiming), + loopRunnerType, runners[index] = new PlayerLoopRunner(playerLoopTiming)); + } + else + { + copyList[i].subSystemList = RemoveRunner(copyList[i], loopRunnerYieldType, loopRunnerType); + } + } + + public static void Initialize(ref PlayerLoopSystem playerLoop, InjectPlayerLoopTimings injectTimings = InjectPlayerLoopTimings.All) + { +#if UNITY_2020_2_OR_NEWER + yielders = new ContinuationQueue[16]; + runners = new PlayerLoopRunner[16]; +#else + yielders = new ContinuationQueue[14]; + runners = new PlayerLoopRunner[14]; +#endif + + var copyList = playerLoop.subSystemList.ToArray(); + + // Initialization + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.Initialization), + InjectPlayerLoopTimings.Initialization, 0, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldInitialization), typeof(UniTaskLoopRunners.UniTaskLoopRunnerInitialization), PlayerLoopTiming.Initialization); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.Initialization), + InjectPlayerLoopTimings.LastInitialization, 1, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldInitialization), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastInitialization), PlayerLoopTiming.LastInitialization); + + // EarlyUpdate + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.EarlyUpdate), + InjectPlayerLoopTimings.EarlyUpdate, 2, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldEarlyUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerEarlyUpdate), PlayerLoopTiming.EarlyUpdate); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.EarlyUpdate), + InjectPlayerLoopTimings.LastEarlyUpdate, 3, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldEarlyUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastEarlyUpdate), PlayerLoopTiming.LastEarlyUpdate); + + // FixedUpdate + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.FixedUpdate), + InjectPlayerLoopTimings.FixedUpdate, 4, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldFixedUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerFixedUpdate), PlayerLoopTiming.FixedUpdate); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.FixedUpdate), + InjectPlayerLoopTimings.LastFixedUpdate, 5, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldFixedUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastFixedUpdate), PlayerLoopTiming.LastFixedUpdate); + + // PreUpdate + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.PreUpdate), + InjectPlayerLoopTimings.PreUpdate, 6, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldPreUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerPreUpdate), PlayerLoopTiming.PreUpdate); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.PreUpdate), + InjectPlayerLoopTimings.LastPreUpdate, 7, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldPreUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastPreUpdate), PlayerLoopTiming.LastPreUpdate); + + // Update + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.Update), + InjectPlayerLoopTimings.Update, 8, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerUpdate), PlayerLoopTiming.Update); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.Update), + InjectPlayerLoopTimings.LastUpdate, 9, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastUpdate), PlayerLoopTiming.LastUpdate); + + // PreLateUpdate + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.PreLateUpdate), + InjectPlayerLoopTimings.PreLateUpdate, 10, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldPreLateUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerPreLateUpdate), PlayerLoopTiming.PreLateUpdate); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.PreLateUpdate), + InjectPlayerLoopTimings.LastPreLateUpdate, 11, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldPreLateUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastPreLateUpdate), PlayerLoopTiming.LastPreLateUpdate); + + // PostLateUpdate + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.PostLateUpdate), + InjectPlayerLoopTimings.PostLateUpdate, 12, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldPostLateUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerPostLateUpdate), PlayerLoopTiming.PostLateUpdate); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.PostLateUpdate), + InjectPlayerLoopTimings.LastPostLateUpdate, 13, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldPostLateUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastPostLateUpdate), PlayerLoopTiming.LastPostLateUpdate); + +#if UNITY_2020_2_OR_NEWER + // TimeUpdate + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.TimeUpdate), + InjectPlayerLoopTimings.TimeUpdate, 14, true, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerYieldTimeUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerTimeUpdate), PlayerLoopTiming.TimeUpdate); + + InsertLoop(copyList, injectTimings, typeof(PlayerLoopType.TimeUpdate), + InjectPlayerLoopTimings.LastTimeUpdate, 15, false, + typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastYieldTimeUpdate), typeof(UniTaskLoopRunners.UniTaskLoopRunnerLastTimeUpdate), PlayerLoopTiming.LastTimeUpdate); +#endif + + // Insert UniTaskSynchronizationContext to Update loop + var i = FindLoopSystemIndex(copyList, typeof(PlayerLoopType.Update)); + copyList[i].subSystemList = InsertUniTaskSynchronizationContext(copyList[i]); + + playerLoop.subSystemList = copyList; + PlayerLoop.SetPlayerLoop(playerLoop); + } + + public static void AddAction(PlayerLoopTiming timing, IPlayerLoopItem action) + { + var runner = runners[(int)timing]; + if (runner == null) + { + ThrowInvalidLoopTiming(timing); + } + runner.AddAction(action); + } + + static void ThrowInvalidLoopTiming(PlayerLoopTiming playerLoopTiming) + { + throw new InvalidOperationException("Target playerLoopTiming is not injected. Please check PlayerLoopHelper.Initialize. PlayerLoopTiming:" + playerLoopTiming); + } + + public static void AddContinuation(PlayerLoopTiming timing, Action continuation) + { + var q = yielders[(int)timing]; + if (q == null) + { + ThrowInvalidLoopTiming(timing); + } + q.Enqueue(continuation); + } + + // Diagnostics helper + +#if UNITY_2019_3_OR_NEWER + + public static void DumpCurrentPlayerLoop() + { + var playerLoop = UnityEngine.LowLevel.PlayerLoop.GetCurrentPlayerLoop(); + + var sb = new System.Text.StringBuilder(); + sb.AppendLine($"PlayerLoop List"); + foreach (var header in playerLoop.subSystemList) + { + sb.AppendFormat("------{0}------", header.type.Name); + sb.AppendLine(); + + if (header.subSystemList is null) + { + sb.AppendFormat("{0} has no subsystems!", header.ToString()); + sb.AppendLine(); + continue; + } + + foreach (var subSystem in header.subSystemList) + { + sb.AppendFormat("{0}", subSystem.type.Name); + sb.AppendLine(); + + if (subSystem.subSystemList != null) + { + UnityEngine.Debug.LogWarning("More Subsystem:" + subSystem.subSystemList.Length); + } + } + } + + UnityEngine.Debug.Log(sb.ToString()); + } + + public static bool IsInjectedUniTaskPlayerLoop() + { + var playerLoop = UnityEngine.LowLevel.PlayerLoop.GetCurrentPlayerLoop(); + + foreach (var header in playerLoop.subSystemList) + { + if (header.subSystemList is null) + { + continue; + } + + foreach (var subSystem in header.subSystemList) + { + if (subSystem.type == typeof(UniTaskLoopRunners.UniTaskLoopRunnerInitialization)) + { + return true; + } + } + } + + return false; + } + +#endif + + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopHelper.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopHelper.cs.meta new file mode 100644 index 00000000..2487ef77 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15fb5b85042f19640b973ce651795aca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopTimer.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopTimer.cs new file mode 100644 index 00000000..f8a877a4 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopTimer.cs @@ -0,0 +1,262 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Threading; +using System; +using Cysharp.Threading.Tasks.Internal; +using UnityEngine; + +namespace Cysharp.Threading.Tasks +{ + public abstract class PlayerLoopTimer : IDisposable, IPlayerLoopItem + { + readonly CancellationToken cancellationToken; + readonly Action timerCallback; + readonly object state; + readonly PlayerLoopTiming playerLoopTiming; + readonly bool periodic; + + bool isRunning; + bool tryStop; + bool isDisposed; + + protected PlayerLoopTimer(bool periodic, PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken, Action timerCallback, object state) + { + this.periodic = periodic; + this.playerLoopTiming = playerLoopTiming; + this.cancellationToken = cancellationToken; + this.timerCallback = timerCallback; + this.state = state; + } + + public static PlayerLoopTimer Create(TimeSpan interval, bool periodic, DelayType delayType, PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken, Action timerCallback, object state) + { +#if UNITY_EDITOR + // force use Realtime. + if (PlayerLoopHelper.IsMainThread && !UnityEditor.EditorApplication.isPlaying) + { + delayType = DelayType.Realtime; + } +#endif + + switch (delayType) + { + case DelayType.UnscaledDeltaTime: + return new IgnoreTimeScalePlayerLoopTimer(interval, periodic, playerLoopTiming, cancellationToken, timerCallback, state); + case DelayType.Realtime: + return new RealtimePlayerLoopTimer(interval, periodic, playerLoopTiming, cancellationToken, timerCallback, state); + case DelayType.DeltaTime: + default: + return new DeltaTimePlayerLoopTimer(interval, periodic, playerLoopTiming, cancellationToken, timerCallback, state); + } + } + + public static PlayerLoopTimer StartNew(TimeSpan interval, bool periodic, DelayType delayType, PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken, Action timerCallback, object state) + { + var timer = Create(interval, periodic, delayType, playerLoopTiming, cancellationToken, timerCallback, state); + timer.Restart(); + return timer; + } + + /// + /// Restart(Reset and Start) timer. + /// + public void Restart() + { + if (isDisposed) throw new ObjectDisposedException(null); + + ResetCore(null); // init state + if (!isRunning) + { + isRunning = true; + PlayerLoopHelper.AddAction(playerLoopTiming, this); + } + tryStop = false; + } + + /// + /// Restart(Reset and Start) and change interval. + /// + public void Restart(TimeSpan interval) + { + if (isDisposed) throw new ObjectDisposedException(null); + + ResetCore(interval); // init state + if (!isRunning) + { + isRunning = true; + PlayerLoopHelper.AddAction(playerLoopTiming, this); + } + tryStop = false; + } + + /// + /// Stop timer. + /// + public void Stop() + { + tryStop = true; + } + + protected abstract void ResetCore(TimeSpan? newInterval); + + public void Dispose() + { + isDisposed = true; + } + + bool IPlayerLoopItem.MoveNext() + { + if (isDisposed) + { + isRunning = false; + return false; + } + if (tryStop) + { + isRunning = false; + return false; + } + if (cancellationToken.IsCancellationRequested) + { + isRunning = false; + return false; + } + + if (!MoveNextCore()) + { + timerCallback(state); + + if (periodic) + { + ResetCore(null); + return true; + } + else + { + isRunning = false; + return false; + } + } + + return true; + } + + protected abstract bool MoveNextCore(); + } + + sealed class DeltaTimePlayerLoopTimer : PlayerLoopTimer + { + int initialFrame; + float elapsed; + float interval; + + public DeltaTimePlayerLoopTimer(TimeSpan interval, bool periodic, PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken, Action timerCallback, object state) + : base(periodic, playerLoopTiming, cancellationToken, timerCallback, state) + { + ResetCore(interval); + } + + protected override bool MoveNextCore() + { + if (elapsed == 0.0f) + { + if (initialFrame == Time.frameCount) + { + return true; + } + } + + elapsed += Time.deltaTime; + if (elapsed >= interval) + { + return false; + } + + return true; + } + + protected override void ResetCore(TimeSpan? interval) + { + this.elapsed = 0.0f; + this.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + if (interval != null) + { + this.interval = (float)interval.Value.TotalSeconds; + } + } + } + + sealed class IgnoreTimeScalePlayerLoopTimer : PlayerLoopTimer + { + int initialFrame; + float elapsed; + float interval; + + public IgnoreTimeScalePlayerLoopTimer(TimeSpan interval, bool periodic, PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken, Action timerCallback, object state) + : base(periodic, playerLoopTiming, cancellationToken, timerCallback, state) + { + ResetCore(interval); + } + + protected override bool MoveNextCore() + { + if (elapsed == 0.0f) + { + if (initialFrame == Time.frameCount) + { + return true; + } + } + + elapsed += Time.unscaledDeltaTime; + if (elapsed >= interval) + { + return false; + } + + return true; + } + + protected override void ResetCore(TimeSpan? interval) + { + this.elapsed = 0.0f; + this.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + if (interval != null) + { + this.interval = (float)interval.Value.TotalSeconds; + } + } + } + + sealed class RealtimePlayerLoopTimer : PlayerLoopTimer + { + ValueStopwatch stopwatch; + long intervalTicks; + + public RealtimePlayerLoopTimer(TimeSpan interval, bool periodic, PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken, Action timerCallback, object state) + : base(periodic, playerLoopTiming, cancellationToken, timerCallback, state) + { + ResetCore(interval); + } + + protected override bool MoveNextCore() + { + if (stopwatch.ElapsedTicks >= intervalTicks) + { + return false; + } + + return true; + } + + protected override void ResetCore(TimeSpan? interval) + { + this.stopwatch = ValueStopwatch.StartNew(); + if (interval != null) + { + this.intervalTicks = interval.Value.Ticks; + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopTimer.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopTimer.cs.meta new file mode 100644 index 00000000..eb2b50a0 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/PlayerLoopTimer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57095a17fdca7ee4380450910afc7f26 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Progress.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Progress.cs new file mode 100644 index 00000000..ed112902 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Progress.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + /// + /// Lightweight IProgress[T] factory. + /// + public static class Progress + { + public static IProgress Create(Action handler) + { + if (handler == null) return NullProgress.Instance; + return new AnonymousProgress(handler); + } + + public static IProgress CreateOnlyValueChanged(Action handler, IEqualityComparer comparer = null) + { + if (handler == null) return NullProgress.Instance; +#if UNITY_2018_3_OR_NEWER + return new OnlyValueChangedProgress(handler, comparer ?? UnityEqualityComparer.GetDefault()); +#else + return new OnlyValueChangedProgress(handler, comparer ?? EqualityComparer.Default); +#endif + } + + sealed class NullProgress : IProgress + { + public static readonly IProgress Instance = new NullProgress(); + + NullProgress() + { + + } + + public void Report(T value) + { + } + } + + sealed class AnonymousProgress : IProgress + { + readonly Action action; + + public AnonymousProgress(Action action) + { + this.action = action; + } + + public void Report(T value) + { + action(value); + } + } + + sealed class OnlyValueChangedProgress : IProgress + { + readonly Action action; + readonly IEqualityComparer comparer; + bool isFirstCall; + T latestValue; + + public OnlyValueChangedProgress(Action action, IEqualityComparer comparer) + { + this.action = action; + this.comparer = comparer; + this.isFirstCall = true; + } + + public void Report(T value) + { + if (isFirstCall) + { + isFirstCall = false; + } + else if (comparer.Equals(value, latestValue)) + { + return; + } + + latestValue = value; + action(value); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Progress.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Progress.cs.meta new file mode 100644 index 00000000..f0e1f197 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Progress.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3377e2ae934ed54fb8fd5388e2d9eb9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/TaskPool.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/TaskPool.cs new file mode 100644 index 00000000..e1035598 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/TaskPool.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + // internally used but public, allow to user create custom operator with pooling. + + public static class TaskPool + { + internal static int MaxPoolSize; + + // avoid to use ConcurrentDictionary for safety of WebGL build. + static Dictionary> sizes = new Dictionary>(); + + static TaskPool() + { + try + { + var value = Environment.GetEnvironmentVariable("UNITASK_MAX_POOLSIZE"); + if (value != null) + { + if (int.TryParse(value, out var size)) + { + MaxPoolSize = size; + return; + } + } + } + catch { } + + MaxPoolSize = int.MaxValue; + } + + public static void SetMaxPoolSize(int maxPoolSize) + { + MaxPoolSize = maxPoolSize; + } + + public static IEnumerable<(Type, int)> GetCacheSizeInfo() + { + lock (sizes) + { + foreach (var item in sizes) + { + yield return (item.Key, item.Value()); + } + } + } + + public static void RegisterSizeGetter(Type type, Func getSize) + { + lock (sizes) + { + sizes[type] = getSize; + } + } + } + + public interface ITaskPoolNode + { + ref T NextNode { get; } + } + + // mutable struct, don't mark readonly. + [StructLayout(LayoutKind.Auto)] + public struct TaskPool + where T : class, ITaskPoolNode + { + int gate; + int size; + T root; + + public int Size => size; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPop(out T result) + { + if (Interlocked.CompareExchange(ref gate, 1, 0) == 0) + { + var v = root; + if (!(v is null)) + { + ref var nextNode = ref v.NextNode; + root = nextNode; + nextNode = null; + size--; + result = v; + Volatile.Write(ref gate, 0); + return true; + } + + Volatile.Write(ref gate, 0); + } + result = default; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryPush(T item) + { + if (Interlocked.CompareExchange(ref gate, 1, 0) == 0) + { + if (size < TaskPool.MaxPoolSize) + { + item.NextNode = root; + root = item; + size++; + Volatile.Write(ref gate, 0); + return true; + } + else + { + Volatile.Write(ref gate, 0); + } + } + return false; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/TaskPool.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/TaskPool.cs.meta new file mode 100644 index 00000000..94c78058 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/TaskPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 19f4e6575150765449cc99f25f06f25f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/TimeoutController.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/TimeoutController.cs new file mode 100644 index 00000000..faca3478 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/TimeoutController.cs @@ -0,0 +1,129 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + // CancellationTokenSource itself can not reuse but CancelAfter(Timeout.InfiniteTimeSpan) allows reuse if did not reach timeout. + // Similar discussion: + // https://github.com/dotnet/runtime/issues/4694 + // https://github.com/dotnet/runtime/issues/48492 + // This TimeoutController emulate similar implementation, using CancelAfterSlim; to achieve zero allocation timeout. + + public sealed class TimeoutController : IDisposable + { + readonly static Action CancelCancellationTokenSourceStateDelegate = new Action(CancelCancellationTokenSourceState); + + static void CancelCancellationTokenSourceState(object state) + { + var cts = (CancellationTokenSource)state; + cts.Cancel(); + } + + CancellationTokenSource timeoutSource; + CancellationTokenSource linkedSource; + PlayerLoopTimer timer; + bool isDisposed; + + readonly DelayType delayType; + readonly PlayerLoopTiming delayTiming; + readonly CancellationTokenSource originalLinkCancellationTokenSource; + + public TimeoutController(DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) + { + this.timeoutSource = new CancellationTokenSource(); + this.originalLinkCancellationTokenSource = null; + this.linkedSource = null; + this.delayType = delayType; + this.delayTiming = delayTiming; + } + + public TimeoutController(CancellationTokenSource linkCancellationTokenSource, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update) + { + this.timeoutSource = new CancellationTokenSource(); + this.originalLinkCancellationTokenSource = linkCancellationTokenSource; + this.linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, linkCancellationTokenSource.Token); + this.delayType = delayType; + this.delayTiming = delayTiming; + } + + public CancellationToken Timeout(int millisecondsTimeout) + { + return Timeout(TimeSpan.FromMilliseconds(millisecondsTimeout)); + } + + public CancellationToken Timeout(TimeSpan timeout) + { + if (originalLinkCancellationTokenSource != null && originalLinkCancellationTokenSource.IsCancellationRequested) + { + return originalLinkCancellationTokenSource.Token; + } + + // Timeouted, create new source and timer. + if (timeoutSource.IsCancellationRequested) + { + timeoutSource.Dispose(); + timeoutSource = new CancellationTokenSource(); + if (linkedSource != null) + { + this.linkedSource.Cancel(); + this.linkedSource.Dispose(); + this.linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, originalLinkCancellationTokenSource.Token); + } + + timer?.Dispose(); + timer = null; + } + + var useSource = (linkedSource != null) ? linkedSource : timeoutSource; + var token = useSource.Token; + if (timer == null) + { + // Timer complete => timeoutSource.Cancel() -> linkedSource will be canceled. + // (linked)token is canceled => stop timer + timer = PlayerLoopTimer.StartNew(timeout, false, delayType, delayTiming, token, CancelCancellationTokenSourceStateDelegate, timeoutSource); + } + else + { + timer.Restart(timeout); + } + + return token; + } + + public bool IsTimeout() + { + return timeoutSource.IsCancellationRequested; + } + + public void Reset() + { + timer?.Stop(); + } + + public void Dispose() + { + if (isDisposed) return; + + try + { + // stop timer. + timer?.Dispose(); + + // cancel and dispose. + timeoutSource.Cancel(); + timeoutSource.Dispose(); + if (linkedSource != null) + { + linkedSource.Cancel(); + linkedSource.Dispose(); + } + } + finally + { + isDisposed = true; + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/TimeoutController.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/TimeoutController.cs.meta new file mode 100644 index 00000000..4f3d16d9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/TimeoutController.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6347ab34d2db6d744a654e8d62d96b96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/TriggerEvent.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/TriggerEvent.cs new file mode 100644 index 00000000..0b817fe3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/TriggerEvent.cs @@ -0,0 +1,291 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public interface ITriggerHandler + { + void OnNext(T value); + void OnError(Exception ex); + void OnCompleted(); + void OnCanceled(CancellationToken cancellationToken); + + // set/get from TriggerEvent + ITriggerHandler Prev { get; set; } + ITriggerHandler Next { get; set; } + } + + // be careful to use, itself is struct. + public struct TriggerEvent + { + ITriggerHandler head; // head.prev is last + ITriggerHandler iteratingHead; + ITriggerHandler iteratingNode; + + void LogError(Exception ex) + { +#if UNITY_2018_3_OR_NEWER + UnityEngine.Debug.LogException(ex); +#else + Console.WriteLine(ex); +#endif + } + + public void SetResult(T value) + { + if (iteratingNode != null) + { + throw new InvalidOperationException("Can not trigger itself in iterating."); + } + + var h = head; + while (h != null) + { + iteratingNode = h; + + try + { + h.OnNext(value); + } + catch (Exception ex) + { + LogError(ex); + Remove(h); + } + + // If `h` itself is removed by OnNext, h.Next is null. + // Therefore, instead of looking at h.Next, the `iteratingNode` reference itself is replaced. + h = h == iteratingNode ? h.Next : iteratingNode; + } + + iteratingNode = null; + if (iteratingHead != null) + { + Add(iteratingHead); + iteratingHead = null; + } + } + + public void SetCanceled(CancellationToken cancellationToken) + { + if (iteratingNode != null) + { + throw new InvalidOperationException("Can not trigger itself in iterating."); + } + + var h = head; + while (h != null) + { + iteratingNode = h; + try + { + h.OnCanceled(cancellationToken); + } + catch (Exception ex) + { + LogError(ex); + } + + var next = h == iteratingNode ? h.Next : iteratingNode; + iteratingNode = null; + Remove(h); + h = next; + } + + iteratingNode = null; + if (iteratingHead != null) + { + Add(iteratingHead); + iteratingHead = null; + } + } + + public void SetCompleted() + { + if (iteratingNode != null) + { + throw new InvalidOperationException("Can not trigger itself in iterating."); + } + + var h = head; + while (h != null) + { + iteratingNode = h; + try + { + h.OnCompleted(); + } + catch (Exception ex) + { + LogError(ex); + } + + var next = h == iteratingNode ? h.Next : iteratingNode; + iteratingNode = null; + Remove(h); + h = next; + } + + iteratingNode = null; + if (iteratingHead != null) + { + Add(iteratingHead); + iteratingHead = null; + } + } + + public void SetError(Exception exception) + { + if (iteratingNode != null) + { + throw new InvalidOperationException("Can not trigger itself in iterating."); + } + + var h = head; + while (h != null) + { + iteratingNode = h; + try + { + h.OnError(exception); + } + catch (Exception ex) + { + LogError(ex); + } + + var next = h == iteratingNode ? h.Next : iteratingNode; + iteratingNode = null; + Remove(h); + h = next; + } + + iteratingNode = null; + if (iteratingHead != null) + { + Add(iteratingHead); + iteratingHead = null; + } + } + + public void Add(ITriggerHandler handler) + { + if (handler == null) throw new ArgumentNullException(nameof(handler)); + + // zero node. + if (head == null) + { + head = handler; + return; + } + + if (iteratingNode != null) + { + if (iteratingHead == null) + { + iteratingHead = handler; + return; + } + + var last = iteratingHead.Prev; + if (last == null) + { + // single node. + iteratingHead.Prev = handler; + iteratingHead.Next = handler; + handler.Prev = iteratingHead; + } + else + { + // multi node + iteratingHead.Prev = handler; + last.Next = handler; + handler.Prev = last; + } + } + else + { + var last = head.Prev; + if (last == null) + { + // single node. + head.Prev = handler; + head.Next = handler; + handler.Prev = head; + } + else + { + // multi node + head.Prev = handler; + last.Next = handler; + handler.Prev = last; + } + } + } + + public void Remove(ITriggerHandler handler) + { + if (handler == null) throw new ArgumentNullException(nameof(handler)); + + var prev = handler.Prev; + var next = handler.Next; + + if (next != null) + { + next.Prev = prev; + } + + if (handler == head) + { + head = next; + } + // when handler is head, prev indicate last so don't use it. + else if (prev != null) + { + prev.Next = next; + } + + if (handler == iteratingNode) + { + iteratingNode = next; + } + if (handler == iteratingHead) + { + iteratingHead = next; + } + + if (head != null) + { + if (head.Prev == handler) + { + if (prev != head) + { + head.Prev = prev; + } + else + { + head.Prev = null; + } + } + } + + if (iteratingHead != null) + { + if (iteratingHead.Prev == handler) + { + if (prev != iteratingHead.Prev) + { + iteratingHead.Prev = prev; + } + else + { + iteratingHead.Prev = null; + } + } + } + + handler.Prev = null; + handler.Next = null; + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/TriggerEvent.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/TriggerEvent.cs.meta new file mode 100644 index 00000000..bbd47af7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/TriggerEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f68b22bb8f66f5c4885f9bd3c4fc43ed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers.meta new file mode 100644 index 00000000..b5ea2dc1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d757a6f27b7332a4b8d3ca20190550cd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncAwakeTrigger.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncAwakeTrigger.cs new file mode 100644 index 00000000..a734f29d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncAwakeTrigger.cs @@ -0,0 +1,32 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Triggers +{ + public static partial class AsyncTriggerExtensions + { + public static AsyncAwakeTrigger GetAsyncAwakeTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncAwakeTrigger GetAsyncAwakeTrigger(this Component component) + { + return component.gameObject.GetAsyncAwakeTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncAwakeTrigger : AsyncTriggerBase + { + public UniTask AwakeAsync() + { + if (calledAwake) return UniTask.CompletedTask; + + return ((IAsyncOneShotTrigger)new AsyncTriggerHandler(this, true)).OneShotAsync(); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncAwakeTrigger.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncAwakeTrigger.cs.meta new file mode 100644 index 00000000..097fdb61 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncAwakeTrigger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef2840a2586894741a0ae211b8fd669b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncDestroyTrigger.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncDestroyTrigger.cs new file mode 100644 index 00000000..77c92859 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncDestroyTrigger.cs @@ -0,0 +1,95 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Triggers +{ + public static partial class AsyncTriggerExtensions + { + public static AsyncDestroyTrigger GetAsyncDestroyTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDestroyTrigger GetAsyncDestroyTrigger(this Component component) + { + return component.gameObject.GetAsyncDestroyTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDestroyTrigger : MonoBehaviour + { + bool awakeCalled = false; + bool called = false; + CancellationTokenSource cancellationTokenSource; + + public CancellationToken CancellationToken + { + get + { + if (cancellationTokenSource == null) + { + cancellationTokenSource = new CancellationTokenSource(); + if (!awakeCalled) + { + PlayerLoopHelper.AddAction(PlayerLoopTiming.Update, new AwakeMonitor(this)); + } + } + return cancellationTokenSource.Token; + } + } + + void Awake() + { + awakeCalled = true; + } + + void OnDestroy() + { + called = true; + + cancellationTokenSource?.Cancel(); + cancellationTokenSource?.Dispose(); + } + + public UniTask OnDestroyAsync() + { + if (called) return UniTask.CompletedTask; + + var tcs = new UniTaskCompletionSource(); + + // OnDestroy = Called Cancel. + CancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var tcs2 = (UniTaskCompletionSource)state; + tcs2.TrySetResult(); + }, tcs); + + return tcs.Task; + } + + class AwakeMonitor : IPlayerLoopItem + { + readonly AsyncDestroyTrigger trigger; + + public AwakeMonitor(AsyncDestroyTrigger trigger) + { + this.trigger = trigger; + } + + public bool MoveNext() + { + if (trigger.called || trigger.awakeCalled) return false; + if (trigger == null) + { + trigger.OnDestroy(); + return false; + } + return true; + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncDestroyTrigger.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncDestroyTrigger.cs.meta new file mode 100644 index 00000000..64500494 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncDestroyTrigger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f4afdcb1cbadf954ba8b1cf465429e17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncStartTrigger.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncStartTrigger.cs new file mode 100644 index 00000000..63da82aa --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncStartTrigger.cs @@ -0,0 +1,38 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Triggers +{ + public static partial class AsyncTriggerExtensions + { + public static AsyncStartTrigger GetAsyncStartTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncStartTrigger GetAsyncStartTrigger(this Component component) + { + return component.gameObject.GetAsyncStartTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncStartTrigger : AsyncTriggerBase + { + bool called; + + void Start() + { + called = true; + RaiseEvent(AsyncUnit.Default); + } + + public UniTask StartAsync() + { + if (called) return UniTask.CompletedTask; + + return ((IAsyncOneShotTrigger)new AsyncTriggerHandler(this, true)).OneShotAsync(); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncStartTrigger.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncStartTrigger.cs.meta new file mode 100644 index 00000000..9ef06e8e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncStartTrigger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4fd0f75e54ec3d4fbcb7fc65b11646b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerBase.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerBase.cs new file mode 100644 index 00000000..fb6ca6ef --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerBase.cs @@ -0,0 +1,310 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks.Triggers +{ + public abstract class AsyncTriggerBase : MonoBehaviour, IUniTaskAsyncEnumerable + { + TriggerEvent triggerEvent; + + internal protected bool calledAwake; + internal protected bool calledDestroy; + + void Awake() + { + calledAwake = true; + } + + void OnDestroy() + { + if (calledDestroy) return; + calledDestroy = true; + + triggerEvent.SetCompleted(); + } + + internal void AddHandler(ITriggerHandler handler) + { + if (!calledAwake) + { + PlayerLoopHelper.AddAction(PlayerLoopTiming.Update, new AwakeMonitor(this)); + } + + triggerEvent.Add(handler); + } + + internal void RemoveHandler(ITriggerHandler handler) + { + if (!calledAwake) + { + PlayerLoopHelper.AddAction(PlayerLoopTiming.Update, new AwakeMonitor(this)); + } + + triggerEvent.Remove(handler); + } + + protected void RaiseEvent(T value) + { + triggerEvent.SetResult(value); + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new AsyncTriggerEnumerator(this, cancellationToken); + } + + sealed class AsyncTriggerEnumerator : MoveNextSource, IUniTaskAsyncEnumerator, ITriggerHandler + { + static Action cancellationCallback = CancellationCallback; + + readonly AsyncTriggerBase parent; + CancellationToken cancellationToken; + CancellationTokenRegistration registration; + bool called; + bool isDisposed; + + public AsyncTriggerEnumerator(AsyncTriggerBase parent, CancellationToken cancellationToken) + { + this.parent = parent; + this.cancellationToken = cancellationToken; + } + + public void OnCanceled(CancellationToken cancellationToken = default) + { + completionSource.TrySetCanceled(cancellationToken); + } + + public void OnNext(T value) + { + Current = value; + completionSource.TrySetResult(true); + } + + public void OnCompleted() + { + completionSource.TrySetResult(false); + } + + public void OnError(Exception ex) + { + completionSource.TrySetException(ex); + } + + static void CancellationCallback(object state) + { + var self = (AsyncTriggerEnumerator)state; + self.DisposeAsync().Forget(); // sync + + self.completionSource.TrySetCanceled(self.cancellationToken); + } + + public T Current { get; private set; } + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (!called) + { + called = true; + + TaskTracker.TrackActiveTask(this, 3); + parent.AddHandler(this); + if (cancellationToken.CanBeCanceled) + { + registration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + } + + return new UniTask(this, completionSource.Version); + } + + public UniTask DisposeAsync() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + registration.Dispose(); + parent.RemoveHandler(this); + } + + return default; + } + } + + class AwakeMonitor : IPlayerLoopItem + { + readonly AsyncTriggerBase trigger; + + public AwakeMonitor(AsyncTriggerBase trigger) + { + this.trigger = trigger; + } + + public bool MoveNext() + { + if (trigger.calledAwake) return false; + if (trigger == null) + { + trigger.OnDestroy(); + return false; + } + return true; + } + } + } + + public interface IAsyncOneShotTrigger + { + UniTask OneShotAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOneShotTrigger + { + UniTask IAsyncOneShotTrigger.OneShotAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)this, core.Version); + } + } + + public sealed partial class AsyncTriggerHandler : IUniTaskSource, ITriggerHandler, IDisposable + { + static Action cancellationCallback = CancellationCallback; + + readonly AsyncTriggerBase trigger; + + CancellationToken cancellationToken; + CancellationTokenRegistration registration; + bool isDisposed; + bool callOnce; + + UniTaskCompletionSourceCore core; + + internal CancellationToken CancellationToken => cancellationToken; + + ITriggerHandler ITriggerHandler.Prev { get; set; } + ITriggerHandler ITriggerHandler.Next { get; set; } + + internal AsyncTriggerHandler(AsyncTriggerBase trigger, bool callOnce) + { + if (cancellationToken.IsCancellationRequested) + { + isDisposed = true; + return; + } + + this.trigger = trigger; + this.cancellationToken = default; + this.registration = default; + this.callOnce = callOnce; + + trigger.AddHandler(this); + + TaskTracker.TrackActiveTask(this, 3); + } + + internal AsyncTriggerHandler(AsyncTriggerBase trigger, CancellationToken cancellationToken, bool callOnce) + { + if (cancellationToken.IsCancellationRequested) + { + isDisposed = true; + return; + } + + this.trigger = trigger; + this.cancellationToken = cancellationToken; + this.callOnce = callOnce; + + trigger.AddHandler(this); + + if (cancellationToken.CanBeCanceled) + { + registration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + + TaskTracker.TrackActiveTask(this, 3); + } + + static void CancellationCallback(object state) + { + var self = (AsyncTriggerHandler)state; + self.Dispose(); + + self.core.TrySetCanceled(self.cancellationToken); + } + + public void Dispose() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + registration.Dispose(); + trigger.RemoveHandler(this); + } + } + + T IUniTaskSource.GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (callOnce) + { + Dispose(); + } + } + } + + void ITriggerHandler.OnNext(T value) + { + core.TrySetResult(value); + } + + void ITriggerHandler.OnCanceled(CancellationToken cancellationToken) + { + core.TrySetCanceled(cancellationToken); + } + + void ITriggerHandler.OnCompleted() + { + core.TrySetCanceled(CancellationToken.None); + } + + void ITriggerHandler.OnError(Exception ex) + { + core.TrySetException(ex); + } + + void IUniTaskSource.GetResult(short token) + { + ((IUniTaskSource)this).GetResult(token); + } + + UniTaskStatus IUniTaskSource.GetStatus(short token) + { + return core.GetStatus(token); + } + + UniTaskStatus IUniTaskSource.UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerBase.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerBase.cs.meta new file mode 100644 index 00000000..e101ea2d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c0c2bcee832c6641b25949c412f020f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerExtensions.cs new file mode 100644 index 00000000..bad5a046 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerExtensions.cs @@ -0,0 +1,102 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Threading; +using UnityEngine; +using Cysharp.Threading.Tasks.Triggers; + +namespace Cysharp.Threading.Tasks +{ + public static class UniTaskCancellationExtensions + { +#if UNITY_2022_2_OR_NEWER + + /// This CancellationToken is canceled when the MonoBehaviour will be destroyed. + public static CancellationToken GetCancellationTokenOnDestroy(this MonoBehaviour monoBehaviour) + { + return monoBehaviour.destroyCancellationToken; + } + +#endif + + /// This CancellationToken is canceled when the MonoBehaviour will be destroyed. + public static CancellationToken GetCancellationTokenOnDestroy(this GameObject gameObject) + { + return gameObject.GetAsyncDestroyTrigger().CancellationToken; + } + + /// This CancellationToken is canceled when the MonoBehaviour will be destroyed. + public static CancellationToken GetCancellationTokenOnDestroy(this Component component) + { +#if UNITY_2022_2_OR_NEWER + if (component is MonoBehaviour mb) + { + return mb.destroyCancellationToken; + } +#endif + + return component.GetAsyncDestroyTrigger().CancellationToken; + } + } +} + +namespace Cysharp.Threading.Tasks.Triggers +{ + public static partial class AsyncTriggerExtensions + { + // Util. + + static T GetOrAddComponent(GameObject gameObject) + where T : Component + { +#if UNITY_2019_2_OR_NEWER + if (!gameObject.TryGetComponent(out var component)) + { + component = gameObject.AddComponent(); + } +#else + var component = gameObject.GetComponent(); + if (component == null) + { + component = gameObject.AddComponent(); + } +#endif + + return component; + } + + // Special for single operation. + + /// This function is called when the MonoBehaviour will be destroyed. + public static UniTask OnDestroyAsync(this GameObject gameObject) + { + return gameObject.GetAsyncDestroyTrigger().OnDestroyAsync(); + } + + /// This function is called when the MonoBehaviour will be destroyed. + public static UniTask OnDestroyAsync(this Component component) + { + return component.GetAsyncDestroyTrigger().OnDestroyAsync(); + } + + public static UniTask StartAsync(this GameObject gameObject) + { + return gameObject.GetAsyncStartTrigger().StartAsync(); + } + + public static UniTask StartAsync(this Component component) + { + return component.GetAsyncStartTrigger().StartAsync(); + } + + public static UniTask AwakeAsync(this GameObject gameObject) + { + return gameObject.GetAsyncAwakeTrigger().AwakeAsync(); + } + + public static UniTask AwakeAsync(this Component component) + { + return component.GetAsyncAwakeTrigger().AwakeAsync(); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerExtensions.cs.meta new file mode 100644 index 00000000..348783dd --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/AsyncTriggerExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 59b61dbea1562a84fb7a38ae0a0a0f88 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs new file mode 100644 index 00000000..6ef50146 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs @@ -0,0 +1,4457 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System.Threading; +using UnityEngine; +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT +using UnityEngine.EventSystems; +#endif + +namespace Cysharp.Threading.Tasks.Triggers +{ +#region FixedUpdate + + public interface IAsyncFixedUpdateHandler + { + UniTask FixedUpdateAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncFixedUpdateHandler + { + UniTask IAsyncFixedUpdateHandler.FixedUpdateAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncFixedUpdateTrigger GetAsyncFixedUpdateTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncFixedUpdateTrigger GetAsyncFixedUpdateTrigger(this Component component) + { + return component.gameObject.GetAsyncFixedUpdateTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncFixedUpdateTrigger : AsyncTriggerBase + { + void FixedUpdate() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncFixedUpdateHandler GetFixedUpdateAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncFixedUpdateHandler GetFixedUpdateAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask FixedUpdateAsync() + { + return ((IAsyncFixedUpdateHandler)new AsyncTriggerHandler(this, true)).FixedUpdateAsync(); + } + + public UniTask FixedUpdateAsync(CancellationToken cancellationToken) + { + return ((IAsyncFixedUpdateHandler)new AsyncTriggerHandler(this, cancellationToken, true)).FixedUpdateAsync(); + } + } +#endregion + +#region LateUpdate + + public interface IAsyncLateUpdateHandler + { + UniTask LateUpdateAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncLateUpdateHandler + { + UniTask IAsyncLateUpdateHandler.LateUpdateAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncLateUpdateTrigger GetAsyncLateUpdateTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncLateUpdateTrigger GetAsyncLateUpdateTrigger(this Component component) + { + return component.gameObject.GetAsyncLateUpdateTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncLateUpdateTrigger : AsyncTriggerBase + { + void LateUpdate() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncLateUpdateHandler GetLateUpdateAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncLateUpdateHandler GetLateUpdateAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask LateUpdateAsync() + { + return ((IAsyncLateUpdateHandler)new AsyncTriggerHandler(this, true)).LateUpdateAsync(); + } + + public UniTask LateUpdateAsync(CancellationToken cancellationToken) + { + return ((IAsyncLateUpdateHandler)new AsyncTriggerHandler(this, cancellationToken, true)).LateUpdateAsync(); + } + } +#endregion + +#region AnimatorIK + + public interface IAsyncOnAnimatorIKHandler + { + UniTask OnAnimatorIKAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnAnimatorIKHandler + { + UniTask IAsyncOnAnimatorIKHandler.OnAnimatorIKAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncAnimatorIKTrigger GetAsyncAnimatorIKTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncAnimatorIKTrigger GetAsyncAnimatorIKTrigger(this Component component) + { + return component.gameObject.GetAsyncAnimatorIKTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncAnimatorIKTrigger : AsyncTriggerBase + { + void OnAnimatorIK(int layerIndex) + { + RaiseEvent((layerIndex)); + } + + public IAsyncOnAnimatorIKHandler GetOnAnimatorIKAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnAnimatorIKHandler GetOnAnimatorIKAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnAnimatorIKAsync() + { + return ((IAsyncOnAnimatorIKHandler)new AsyncTriggerHandler(this, true)).OnAnimatorIKAsync(); + } + + public UniTask OnAnimatorIKAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnAnimatorIKHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnAnimatorIKAsync(); + } + } +#endregion + +#region AnimatorMove + + public interface IAsyncOnAnimatorMoveHandler + { + UniTask OnAnimatorMoveAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnAnimatorMoveHandler + { + UniTask IAsyncOnAnimatorMoveHandler.OnAnimatorMoveAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncAnimatorMoveTrigger GetAsyncAnimatorMoveTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncAnimatorMoveTrigger GetAsyncAnimatorMoveTrigger(this Component component) + { + return component.gameObject.GetAsyncAnimatorMoveTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncAnimatorMoveTrigger : AsyncTriggerBase + { + void OnAnimatorMove() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnAnimatorMoveHandler GetOnAnimatorMoveAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnAnimatorMoveHandler GetOnAnimatorMoveAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnAnimatorMoveAsync() + { + return ((IAsyncOnAnimatorMoveHandler)new AsyncTriggerHandler(this, true)).OnAnimatorMoveAsync(); + } + + public UniTask OnAnimatorMoveAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnAnimatorMoveHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnAnimatorMoveAsync(); + } + } +#endregion + +#region ApplicationFocus + + public interface IAsyncOnApplicationFocusHandler + { + UniTask OnApplicationFocusAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnApplicationFocusHandler + { + UniTask IAsyncOnApplicationFocusHandler.OnApplicationFocusAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncApplicationFocusTrigger GetAsyncApplicationFocusTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncApplicationFocusTrigger GetAsyncApplicationFocusTrigger(this Component component) + { + return component.gameObject.GetAsyncApplicationFocusTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncApplicationFocusTrigger : AsyncTriggerBase + { + void OnApplicationFocus(bool hasFocus) + { + RaiseEvent((hasFocus)); + } + + public IAsyncOnApplicationFocusHandler GetOnApplicationFocusAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnApplicationFocusHandler GetOnApplicationFocusAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnApplicationFocusAsync() + { + return ((IAsyncOnApplicationFocusHandler)new AsyncTriggerHandler(this, true)).OnApplicationFocusAsync(); + } + + public UniTask OnApplicationFocusAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnApplicationFocusHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnApplicationFocusAsync(); + } + } +#endregion + +#region ApplicationPause + + public interface IAsyncOnApplicationPauseHandler + { + UniTask OnApplicationPauseAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnApplicationPauseHandler + { + UniTask IAsyncOnApplicationPauseHandler.OnApplicationPauseAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncApplicationPauseTrigger GetAsyncApplicationPauseTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncApplicationPauseTrigger GetAsyncApplicationPauseTrigger(this Component component) + { + return component.gameObject.GetAsyncApplicationPauseTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncApplicationPauseTrigger : AsyncTriggerBase + { + void OnApplicationPause(bool pauseStatus) + { + RaiseEvent((pauseStatus)); + } + + public IAsyncOnApplicationPauseHandler GetOnApplicationPauseAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnApplicationPauseHandler GetOnApplicationPauseAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnApplicationPauseAsync() + { + return ((IAsyncOnApplicationPauseHandler)new AsyncTriggerHandler(this, true)).OnApplicationPauseAsync(); + } + + public UniTask OnApplicationPauseAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnApplicationPauseHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnApplicationPauseAsync(); + } + } +#endregion + +#region ApplicationQuit + + public interface IAsyncOnApplicationQuitHandler + { + UniTask OnApplicationQuitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnApplicationQuitHandler + { + UniTask IAsyncOnApplicationQuitHandler.OnApplicationQuitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncApplicationQuitTrigger GetAsyncApplicationQuitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncApplicationQuitTrigger GetAsyncApplicationQuitTrigger(this Component component) + { + return component.gameObject.GetAsyncApplicationQuitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncApplicationQuitTrigger : AsyncTriggerBase + { + void OnApplicationQuit() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnApplicationQuitHandler GetOnApplicationQuitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnApplicationQuitHandler GetOnApplicationQuitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnApplicationQuitAsync() + { + return ((IAsyncOnApplicationQuitHandler)new AsyncTriggerHandler(this, true)).OnApplicationQuitAsync(); + } + + public UniTask OnApplicationQuitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnApplicationQuitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnApplicationQuitAsync(); + } + } +#endregion + +#region AudioFilterRead + + public interface IAsyncOnAudioFilterReadHandler + { + UniTask<(float[] data, int channels)> OnAudioFilterReadAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnAudioFilterReadHandler + { + UniTask<(float[] data, int channels)> IAsyncOnAudioFilterReadHandler.OnAudioFilterReadAsync() + { + core.Reset(); + return new UniTask<(float[] data, int channels)>((IUniTaskSource<(float[] data, int channels)>)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncAudioFilterReadTrigger GetAsyncAudioFilterReadTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncAudioFilterReadTrigger GetAsyncAudioFilterReadTrigger(this Component component) + { + return component.gameObject.GetAsyncAudioFilterReadTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncAudioFilterReadTrigger : AsyncTriggerBase<(float[] data, int channels)> + { + void OnAudioFilterRead(float[] data, int channels) + { + RaiseEvent((data, channels)); + } + + public IAsyncOnAudioFilterReadHandler GetOnAudioFilterReadAsyncHandler() + { + return new AsyncTriggerHandler<(float[] data, int channels)>(this, false); + } + + public IAsyncOnAudioFilterReadHandler GetOnAudioFilterReadAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler<(float[] data, int channels)>(this, cancellationToken, false); + } + + public UniTask<(float[] data, int channels)> OnAudioFilterReadAsync() + { + return ((IAsyncOnAudioFilterReadHandler)new AsyncTriggerHandler<(float[] data, int channels)>(this, true)).OnAudioFilterReadAsync(); + } + + public UniTask<(float[] data, int channels)> OnAudioFilterReadAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnAudioFilterReadHandler)new AsyncTriggerHandler<(float[] data, int channels)>(this, cancellationToken, true)).OnAudioFilterReadAsync(); + } + } +#endregion + +#region BecameInvisible + + public interface IAsyncOnBecameInvisibleHandler + { + UniTask OnBecameInvisibleAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnBecameInvisibleHandler + { + UniTask IAsyncOnBecameInvisibleHandler.OnBecameInvisibleAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncBecameInvisibleTrigger GetAsyncBecameInvisibleTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncBecameInvisibleTrigger GetAsyncBecameInvisibleTrigger(this Component component) + { + return component.gameObject.GetAsyncBecameInvisibleTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncBecameInvisibleTrigger : AsyncTriggerBase + { + void OnBecameInvisible() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnBecameInvisibleHandler GetOnBecameInvisibleAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnBecameInvisibleHandler GetOnBecameInvisibleAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnBecameInvisibleAsync() + { + return ((IAsyncOnBecameInvisibleHandler)new AsyncTriggerHandler(this, true)).OnBecameInvisibleAsync(); + } + + public UniTask OnBecameInvisibleAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnBecameInvisibleHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnBecameInvisibleAsync(); + } + } +#endregion + +#region BecameVisible + + public interface IAsyncOnBecameVisibleHandler + { + UniTask OnBecameVisibleAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnBecameVisibleHandler + { + UniTask IAsyncOnBecameVisibleHandler.OnBecameVisibleAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncBecameVisibleTrigger GetAsyncBecameVisibleTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncBecameVisibleTrigger GetAsyncBecameVisibleTrigger(this Component component) + { + return component.gameObject.GetAsyncBecameVisibleTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncBecameVisibleTrigger : AsyncTriggerBase + { + void OnBecameVisible() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnBecameVisibleHandler GetOnBecameVisibleAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnBecameVisibleHandler GetOnBecameVisibleAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnBecameVisibleAsync() + { + return ((IAsyncOnBecameVisibleHandler)new AsyncTriggerHandler(this, true)).OnBecameVisibleAsync(); + } + + public UniTask OnBecameVisibleAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnBecameVisibleHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnBecameVisibleAsync(); + } + } +#endregion + +#region BeforeTransformParentChanged + + public interface IAsyncOnBeforeTransformParentChangedHandler + { + UniTask OnBeforeTransformParentChangedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnBeforeTransformParentChangedHandler + { + UniTask IAsyncOnBeforeTransformParentChangedHandler.OnBeforeTransformParentChangedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncBeforeTransformParentChangedTrigger GetAsyncBeforeTransformParentChangedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncBeforeTransformParentChangedTrigger GetAsyncBeforeTransformParentChangedTrigger(this Component component) + { + return component.gameObject.GetAsyncBeforeTransformParentChangedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncBeforeTransformParentChangedTrigger : AsyncTriggerBase + { + void OnBeforeTransformParentChanged() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnBeforeTransformParentChangedHandler GetOnBeforeTransformParentChangedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnBeforeTransformParentChangedHandler GetOnBeforeTransformParentChangedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnBeforeTransformParentChangedAsync() + { + return ((IAsyncOnBeforeTransformParentChangedHandler)new AsyncTriggerHandler(this, true)).OnBeforeTransformParentChangedAsync(); + } + + public UniTask OnBeforeTransformParentChangedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnBeforeTransformParentChangedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnBeforeTransformParentChangedAsync(); + } + } +#endregion + +#region OnCanvasGroupChanged + + public interface IAsyncOnCanvasGroupChangedHandler + { + UniTask OnCanvasGroupChangedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCanvasGroupChangedHandler + { + UniTask IAsyncOnCanvasGroupChangedHandler.OnCanvasGroupChangedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncOnCanvasGroupChangedTrigger GetAsyncOnCanvasGroupChangedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncOnCanvasGroupChangedTrigger GetAsyncOnCanvasGroupChangedTrigger(this Component component) + { + return component.gameObject.GetAsyncOnCanvasGroupChangedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncOnCanvasGroupChangedTrigger : AsyncTriggerBase + { + void OnCanvasGroupChanged() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnCanvasGroupChangedHandler GetOnCanvasGroupChangedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCanvasGroupChangedHandler GetOnCanvasGroupChangedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCanvasGroupChangedAsync() + { + return ((IAsyncOnCanvasGroupChangedHandler)new AsyncTriggerHandler(this, true)).OnCanvasGroupChangedAsync(); + } + + public UniTask OnCanvasGroupChangedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCanvasGroupChangedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCanvasGroupChangedAsync(); + } + } +#endregion + +#region CollisionEnter +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnCollisionEnterHandler + { + UniTask OnCollisionEnterAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCollisionEnterHandler + { + UniTask IAsyncOnCollisionEnterHandler.OnCollisionEnterAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCollisionEnterTrigger GetAsyncCollisionEnterTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCollisionEnterTrigger GetAsyncCollisionEnterTrigger(this Component component) + { + return component.gameObject.GetAsyncCollisionEnterTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCollisionEnterTrigger : AsyncTriggerBase + { + void OnCollisionEnter(Collision coll) + { + RaiseEvent((coll)); + } + + public IAsyncOnCollisionEnterHandler GetOnCollisionEnterAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCollisionEnterHandler GetOnCollisionEnterAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCollisionEnterAsync() + { + return ((IAsyncOnCollisionEnterHandler)new AsyncTriggerHandler(this, true)).OnCollisionEnterAsync(); + } + + public UniTask OnCollisionEnterAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCollisionEnterHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCollisionEnterAsync(); + } + } +#endif +#endregion + +#region CollisionEnter2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnCollisionEnter2DHandler + { + UniTask OnCollisionEnter2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCollisionEnter2DHandler + { + UniTask IAsyncOnCollisionEnter2DHandler.OnCollisionEnter2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCollisionEnter2DTrigger GetAsyncCollisionEnter2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCollisionEnter2DTrigger GetAsyncCollisionEnter2DTrigger(this Component component) + { + return component.gameObject.GetAsyncCollisionEnter2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCollisionEnter2DTrigger : AsyncTriggerBase + { + void OnCollisionEnter2D(Collision2D coll) + { + RaiseEvent((coll)); + } + + public IAsyncOnCollisionEnter2DHandler GetOnCollisionEnter2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCollisionEnter2DHandler GetOnCollisionEnter2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCollisionEnter2DAsync() + { + return ((IAsyncOnCollisionEnter2DHandler)new AsyncTriggerHandler(this, true)).OnCollisionEnter2DAsync(); + } + + public UniTask OnCollisionEnter2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCollisionEnter2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCollisionEnter2DAsync(); + } + } +#endif +#endregion + +#region CollisionExit +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnCollisionExitHandler + { + UniTask OnCollisionExitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCollisionExitHandler + { + UniTask IAsyncOnCollisionExitHandler.OnCollisionExitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCollisionExitTrigger GetAsyncCollisionExitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCollisionExitTrigger GetAsyncCollisionExitTrigger(this Component component) + { + return component.gameObject.GetAsyncCollisionExitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCollisionExitTrigger : AsyncTriggerBase + { + void OnCollisionExit(Collision coll) + { + RaiseEvent((coll)); + } + + public IAsyncOnCollisionExitHandler GetOnCollisionExitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCollisionExitHandler GetOnCollisionExitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCollisionExitAsync() + { + return ((IAsyncOnCollisionExitHandler)new AsyncTriggerHandler(this, true)).OnCollisionExitAsync(); + } + + public UniTask OnCollisionExitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCollisionExitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCollisionExitAsync(); + } + } +#endif +#endregion + +#region CollisionExit2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnCollisionExit2DHandler + { + UniTask OnCollisionExit2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCollisionExit2DHandler + { + UniTask IAsyncOnCollisionExit2DHandler.OnCollisionExit2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCollisionExit2DTrigger GetAsyncCollisionExit2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCollisionExit2DTrigger GetAsyncCollisionExit2DTrigger(this Component component) + { + return component.gameObject.GetAsyncCollisionExit2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCollisionExit2DTrigger : AsyncTriggerBase + { + void OnCollisionExit2D(Collision2D coll) + { + RaiseEvent((coll)); + } + + public IAsyncOnCollisionExit2DHandler GetOnCollisionExit2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCollisionExit2DHandler GetOnCollisionExit2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCollisionExit2DAsync() + { + return ((IAsyncOnCollisionExit2DHandler)new AsyncTriggerHandler(this, true)).OnCollisionExit2DAsync(); + } + + public UniTask OnCollisionExit2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCollisionExit2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCollisionExit2DAsync(); + } + } +#endif +#endregion + +#region CollisionStay +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnCollisionStayHandler + { + UniTask OnCollisionStayAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCollisionStayHandler + { + UniTask IAsyncOnCollisionStayHandler.OnCollisionStayAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCollisionStayTrigger GetAsyncCollisionStayTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCollisionStayTrigger GetAsyncCollisionStayTrigger(this Component component) + { + return component.gameObject.GetAsyncCollisionStayTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCollisionStayTrigger : AsyncTriggerBase + { + void OnCollisionStay(Collision coll) + { + RaiseEvent((coll)); + } + + public IAsyncOnCollisionStayHandler GetOnCollisionStayAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCollisionStayHandler GetOnCollisionStayAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCollisionStayAsync() + { + return ((IAsyncOnCollisionStayHandler)new AsyncTriggerHandler(this, true)).OnCollisionStayAsync(); + } + + public UniTask OnCollisionStayAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCollisionStayHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCollisionStayAsync(); + } + } +#endif +#endregion + +#region CollisionStay2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnCollisionStay2DHandler + { + UniTask OnCollisionStay2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCollisionStay2DHandler + { + UniTask IAsyncOnCollisionStay2DHandler.OnCollisionStay2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCollisionStay2DTrigger GetAsyncCollisionStay2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCollisionStay2DTrigger GetAsyncCollisionStay2DTrigger(this Component component) + { + return component.gameObject.GetAsyncCollisionStay2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCollisionStay2DTrigger : AsyncTriggerBase + { + void OnCollisionStay2D(Collision2D coll) + { + RaiseEvent((coll)); + } + + public IAsyncOnCollisionStay2DHandler GetOnCollisionStay2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCollisionStay2DHandler GetOnCollisionStay2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCollisionStay2DAsync() + { + return ((IAsyncOnCollisionStay2DHandler)new AsyncTriggerHandler(this, true)).OnCollisionStay2DAsync(); + } + + public UniTask OnCollisionStay2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCollisionStay2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCollisionStay2DAsync(); + } + } +#endif +#endregion + +#region ControllerColliderHit +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnControllerColliderHitHandler + { + UniTask OnControllerColliderHitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnControllerColliderHitHandler + { + UniTask IAsyncOnControllerColliderHitHandler.OnControllerColliderHitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncControllerColliderHitTrigger GetAsyncControllerColliderHitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncControllerColliderHitTrigger GetAsyncControllerColliderHitTrigger(this Component component) + { + return component.gameObject.GetAsyncControllerColliderHitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncControllerColliderHitTrigger : AsyncTriggerBase + { + void OnControllerColliderHit(ControllerColliderHit hit) + { + RaiseEvent((hit)); + } + + public IAsyncOnControllerColliderHitHandler GetOnControllerColliderHitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnControllerColliderHitHandler GetOnControllerColliderHitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnControllerColliderHitAsync() + { + return ((IAsyncOnControllerColliderHitHandler)new AsyncTriggerHandler(this, true)).OnControllerColliderHitAsync(); + } + + public UniTask OnControllerColliderHitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnControllerColliderHitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnControllerColliderHitAsync(); + } + } +#endif +#endregion + +#region Disable + + public interface IAsyncOnDisableHandler + { + UniTask OnDisableAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnDisableHandler + { + UniTask IAsyncOnDisableHandler.OnDisableAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncDisableTrigger GetAsyncDisableTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDisableTrigger GetAsyncDisableTrigger(this Component component) + { + return component.gameObject.GetAsyncDisableTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDisableTrigger : AsyncTriggerBase + { + void OnDisable() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnDisableHandler GetOnDisableAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnDisableHandler GetOnDisableAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnDisableAsync() + { + return ((IAsyncOnDisableHandler)new AsyncTriggerHandler(this, true)).OnDisableAsync(); + } + + public UniTask OnDisableAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnDisableHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnDisableAsync(); + } + } +#endregion + +#region DrawGizmos + + public interface IAsyncOnDrawGizmosHandler + { + UniTask OnDrawGizmosAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnDrawGizmosHandler + { + UniTask IAsyncOnDrawGizmosHandler.OnDrawGizmosAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncDrawGizmosTrigger GetAsyncDrawGizmosTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDrawGizmosTrigger GetAsyncDrawGizmosTrigger(this Component component) + { + return component.gameObject.GetAsyncDrawGizmosTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDrawGizmosTrigger : AsyncTriggerBase + { + void OnDrawGizmos() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnDrawGizmosHandler GetOnDrawGizmosAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnDrawGizmosHandler GetOnDrawGizmosAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnDrawGizmosAsync() + { + return ((IAsyncOnDrawGizmosHandler)new AsyncTriggerHandler(this, true)).OnDrawGizmosAsync(); + } + + public UniTask OnDrawGizmosAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnDrawGizmosHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnDrawGizmosAsync(); + } + } +#endregion + +#region DrawGizmosSelected + + public interface IAsyncOnDrawGizmosSelectedHandler + { + UniTask OnDrawGizmosSelectedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnDrawGizmosSelectedHandler + { + UniTask IAsyncOnDrawGizmosSelectedHandler.OnDrawGizmosSelectedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncDrawGizmosSelectedTrigger GetAsyncDrawGizmosSelectedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDrawGizmosSelectedTrigger GetAsyncDrawGizmosSelectedTrigger(this Component component) + { + return component.gameObject.GetAsyncDrawGizmosSelectedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDrawGizmosSelectedTrigger : AsyncTriggerBase + { + void OnDrawGizmosSelected() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnDrawGizmosSelectedHandler GetOnDrawGizmosSelectedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnDrawGizmosSelectedHandler GetOnDrawGizmosSelectedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnDrawGizmosSelectedAsync() + { + return ((IAsyncOnDrawGizmosSelectedHandler)new AsyncTriggerHandler(this, true)).OnDrawGizmosSelectedAsync(); + } + + public UniTask OnDrawGizmosSelectedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnDrawGizmosSelectedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnDrawGizmosSelectedAsync(); + } + } +#endregion + +#region Enable + + public interface IAsyncOnEnableHandler + { + UniTask OnEnableAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnEnableHandler + { + UniTask IAsyncOnEnableHandler.OnEnableAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncEnableTrigger GetAsyncEnableTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncEnableTrigger GetAsyncEnableTrigger(this Component component) + { + return component.gameObject.GetAsyncEnableTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncEnableTrigger : AsyncTriggerBase + { + void OnEnable() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnEnableHandler GetOnEnableAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnEnableHandler GetOnEnableAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnEnableAsync() + { + return ((IAsyncOnEnableHandler)new AsyncTriggerHandler(this, true)).OnEnableAsync(); + } + + public UniTask OnEnableAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnEnableHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnEnableAsync(); + } + } +#endregion + +#region GUI + + public interface IAsyncOnGUIHandler + { + UniTask OnGUIAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnGUIHandler + { + UniTask IAsyncOnGUIHandler.OnGUIAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncGUITrigger GetAsyncGUITrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncGUITrigger GetAsyncGUITrigger(this Component component) + { + return component.gameObject.GetAsyncGUITrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncGUITrigger : AsyncTriggerBase + { + void OnGUI() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnGUIHandler GetOnGUIAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnGUIHandler GetOnGUIAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnGUIAsync() + { + return ((IAsyncOnGUIHandler)new AsyncTriggerHandler(this, true)).OnGUIAsync(); + } + + public UniTask OnGUIAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnGUIHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnGUIAsync(); + } + } +#endregion + +#region JointBreak +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnJointBreakHandler + { + UniTask OnJointBreakAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnJointBreakHandler + { + UniTask IAsyncOnJointBreakHandler.OnJointBreakAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncJointBreakTrigger GetAsyncJointBreakTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncJointBreakTrigger GetAsyncJointBreakTrigger(this Component component) + { + return component.gameObject.GetAsyncJointBreakTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncJointBreakTrigger : AsyncTriggerBase + { + void OnJointBreak(float breakForce) + { + RaiseEvent((breakForce)); + } + + public IAsyncOnJointBreakHandler GetOnJointBreakAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnJointBreakHandler GetOnJointBreakAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnJointBreakAsync() + { + return ((IAsyncOnJointBreakHandler)new AsyncTriggerHandler(this, true)).OnJointBreakAsync(); + } + + public UniTask OnJointBreakAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnJointBreakHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnJointBreakAsync(); + } + } +#endif +#endregion + +#region JointBreak2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnJointBreak2DHandler + { + UniTask OnJointBreak2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnJointBreak2DHandler + { + UniTask IAsyncOnJointBreak2DHandler.OnJointBreak2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncJointBreak2DTrigger GetAsyncJointBreak2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncJointBreak2DTrigger GetAsyncJointBreak2DTrigger(this Component component) + { + return component.gameObject.GetAsyncJointBreak2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncJointBreak2DTrigger : AsyncTriggerBase + { + void OnJointBreak2D(Joint2D brokenJoint) + { + RaiseEvent((brokenJoint)); + } + + public IAsyncOnJointBreak2DHandler GetOnJointBreak2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnJointBreak2DHandler GetOnJointBreak2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnJointBreak2DAsync() + { + return ((IAsyncOnJointBreak2DHandler)new AsyncTriggerHandler(this, true)).OnJointBreak2DAsync(); + } + + public UniTask OnJointBreak2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnJointBreak2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnJointBreak2DAsync(); + } + } +#endif +#endregion + +#region MouseDown +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseDownHandler + { + UniTask OnMouseDownAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseDownHandler + { + UniTask IAsyncOnMouseDownHandler.OnMouseDownAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseDownTrigger GetAsyncMouseDownTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseDownTrigger GetAsyncMouseDownTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseDownTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseDownTrigger : AsyncTriggerBase + { + void OnMouseDown() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseDownHandler GetOnMouseDownAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseDownHandler GetOnMouseDownAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseDownAsync() + { + return ((IAsyncOnMouseDownHandler)new AsyncTriggerHandler(this, true)).OnMouseDownAsync(); + } + + public UniTask OnMouseDownAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseDownHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseDownAsync(); + } + } +#endif +#endregion + +#region MouseDrag +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseDragHandler + { + UniTask OnMouseDragAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseDragHandler + { + UniTask IAsyncOnMouseDragHandler.OnMouseDragAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseDragTrigger GetAsyncMouseDragTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseDragTrigger GetAsyncMouseDragTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseDragTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseDragTrigger : AsyncTriggerBase + { + void OnMouseDrag() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseDragHandler GetOnMouseDragAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseDragHandler GetOnMouseDragAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseDragAsync() + { + return ((IAsyncOnMouseDragHandler)new AsyncTriggerHandler(this, true)).OnMouseDragAsync(); + } + + public UniTask OnMouseDragAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseDragHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseDragAsync(); + } + } +#endif +#endregion + +#region MouseEnter +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseEnterHandler + { + UniTask OnMouseEnterAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseEnterHandler + { + UniTask IAsyncOnMouseEnterHandler.OnMouseEnterAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseEnterTrigger GetAsyncMouseEnterTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseEnterTrigger GetAsyncMouseEnterTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseEnterTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseEnterTrigger : AsyncTriggerBase + { + void OnMouseEnter() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseEnterHandler GetOnMouseEnterAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseEnterHandler GetOnMouseEnterAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseEnterAsync() + { + return ((IAsyncOnMouseEnterHandler)new AsyncTriggerHandler(this, true)).OnMouseEnterAsync(); + } + + public UniTask OnMouseEnterAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseEnterHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseEnterAsync(); + } + } +#endif +#endregion + +#region MouseExit +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseExitHandler + { + UniTask OnMouseExitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseExitHandler + { + UniTask IAsyncOnMouseExitHandler.OnMouseExitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseExitTrigger GetAsyncMouseExitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseExitTrigger GetAsyncMouseExitTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseExitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseExitTrigger : AsyncTriggerBase + { + void OnMouseExit() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseExitHandler GetOnMouseExitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseExitHandler GetOnMouseExitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseExitAsync() + { + return ((IAsyncOnMouseExitHandler)new AsyncTriggerHandler(this, true)).OnMouseExitAsync(); + } + + public UniTask OnMouseExitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseExitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseExitAsync(); + } + } +#endif +#endregion + +#region MouseOver +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseOverHandler + { + UniTask OnMouseOverAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseOverHandler + { + UniTask IAsyncOnMouseOverHandler.OnMouseOverAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseOverTrigger GetAsyncMouseOverTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseOverTrigger GetAsyncMouseOverTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseOverTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseOverTrigger : AsyncTriggerBase + { + void OnMouseOver() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseOverHandler GetOnMouseOverAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseOverHandler GetOnMouseOverAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseOverAsync() + { + return ((IAsyncOnMouseOverHandler)new AsyncTriggerHandler(this, true)).OnMouseOverAsync(); + } + + public UniTask OnMouseOverAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseOverHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseOverAsync(); + } + } +#endif +#endregion + +#region MouseUp +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseUpHandler + { + UniTask OnMouseUpAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseUpHandler + { + UniTask IAsyncOnMouseUpHandler.OnMouseUpAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseUpTrigger GetAsyncMouseUpTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseUpTrigger GetAsyncMouseUpTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseUpTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseUpTrigger : AsyncTriggerBase + { + void OnMouseUp() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseUpHandler GetOnMouseUpAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseUpHandler GetOnMouseUpAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseUpAsync() + { + return ((IAsyncOnMouseUpHandler)new AsyncTriggerHandler(this, true)).OnMouseUpAsync(); + } + + public UniTask OnMouseUpAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseUpHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseUpAsync(); + } + } +#endif +#endregion + +#region MouseUpAsButton +#if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_METRO) + + public interface IAsyncOnMouseUpAsButtonHandler + { + UniTask OnMouseUpAsButtonAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMouseUpAsButtonHandler + { + UniTask IAsyncOnMouseUpAsButtonHandler.OnMouseUpAsButtonAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMouseUpAsButtonTrigger GetAsyncMouseUpAsButtonTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMouseUpAsButtonTrigger GetAsyncMouseUpAsButtonTrigger(this Component component) + { + return component.gameObject.GetAsyncMouseUpAsButtonTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMouseUpAsButtonTrigger : AsyncTriggerBase + { + void OnMouseUpAsButton() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnMouseUpAsButtonHandler GetOnMouseUpAsButtonAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMouseUpAsButtonHandler GetOnMouseUpAsButtonAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMouseUpAsButtonAsync() + { + return ((IAsyncOnMouseUpAsButtonHandler)new AsyncTriggerHandler(this, true)).OnMouseUpAsButtonAsync(); + } + + public UniTask OnMouseUpAsButtonAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMouseUpAsButtonHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMouseUpAsButtonAsync(); + } + } +#endif +#endregion + +#region ParticleCollision + + public interface IAsyncOnParticleCollisionHandler + { + UniTask OnParticleCollisionAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnParticleCollisionHandler + { + UniTask IAsyncOnParticleCollisionHandler.OnParticleCollisionAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncParticleCollisionTrigger GetAsyncParticleCollisionTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncParticleCollisionTrigger GetAsyncParticleCollisionTrigger(this Component component) + { + return component.gameObject.GetAsyncParticleCollisionTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncParticleCollisionTrigger : AsyncTriggerBase + { + void OnParticleCollision(GameObject other) + { + RaiseEvent((other)); + } + + public IAsyncOnParticleCollisionHandler GetOnParticleCollisionAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnParticleCollisionHandler GetOnParticleCollisionAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnParticleCollisionAsync() + { + return ((IAsyncOnParticleCollisionHandler)new AsyncTriggerHandler(this, true)).OnParticleCollisionAsync(); + } + + public UniTask OnParticleCollisionAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnParticleCollisionHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnParticleCollisionAsync(); + } + } +#endregion + +#region ParticleSystemStopped + + public interface IAsyncOnParticleSystemStoppedHandler + { + UniTask OnParticleSystemStoppedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnParticleSystemStoppedHandler + { + UniTask IAsyncOnParticleSystemStoppedHandler.OnParticleSystemStoppedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncParticleSystemStoppedTrigger GetAsyncParticleSystemStoppedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncParticleSystemStoppedTrigger GetAsyncParticleSystemStoppedTrigger(this Component component) + { + return component.gameObject.GetAsyncParticleSystemStoppedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncParticleSystemStoppedTrigger : AsyncTriggerBase + { + void OnParticleSystemStopped() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnParticleSystemStoppedHandler GetOnParticleSystemStoppedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnParticleSystemStoppedHandler GetOnParticleSystemStoppedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnParticleSystemStoppedAsync() + { + return ((IAsyncOnParticleSystemStoppedHandler)new AsyncTriggerHandler(this, true)).OnParticleSystemStoppedAsync(); + } + + public UniTask OnParticleSystemStoppedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnParticleSystemStoppedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnParticleSystemStoppedAsync(); + } + } +#endregion + +#region ParticleTrigger + + public interface IAsyncOnParticleTriggerHandler + { + UniTask OnParticleTriggerAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnParticleTriggerHandler + { + UniTask IAsyncOnParticleTriggerHandler.OnParticleTriggerAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncParticleTriggerTrigger GetAsyncParticleTriggerTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncParticleTriggerTrigger GetAsyncParticleTriggerTrigger(this Component component) + { + return component.gameObject.GetAsyncParticleTriggerTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncParticleTriggerTrigger : AsyncTriggerBase + { + void OnParticleTrigger() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnParticleTriggerHandler GetOnParticleTriggerAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnParticleTriggerHandler GetOnParticleTriggerAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnParticleTriggerAsync() + { + return ((IAsyncOnParticleTriggerHandler)new AsyncTriggerHandler(this, true)).OnParticleTriggerAsync(); + } + + public UniTask OnParticleTriggerAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnParticleTriggerHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnParticleTriggerAsync(); + } + } +#endregion + +#region ParticleUpdateJobScheduled +#if UNITY_2019_3_OR_NEWER && (!UNITY_2019_1_OR_NEWER || UNITASK_PARTICLESYSTEM_SUPPORT) + + public interface IAsyncOnParticleUpdateJobScheduledHandler + { + UniTask OnParticleUpdateJobScheduledAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnParticleUpdateJobScheduledHandler + { + UniTask IAsyncOnParticleUpdateJobScheduledHandler.OnParticleUpdateJobScheduledAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncParticleUpdateJobScheduledTrigger GetAsyncParticleUpdateJobScheduledTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncParticleUpdateJobScheduledTrigger GetAsyncParticleUpdateJobScheduledTrigger(this Component component) + { + return component.gameObject.GetAsyncParticleUpdateJobScheduledTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncParticleUpdateJobScheduledTrigger : AsyncTriggerBase + { + void OnParticleUpdateJobScheduled(UnityEngine.ParticleSystemJobs.ParticleSystemJobData particles) + { + RaiseEvent((particles)); + } + + public IAsyncOnParticleUpdateJobScheduledHandler GetOnParticleUpdateJobScheduledAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnParticleUpdateJobScheduledHandler GetOnParticleUpdateJobScheduledAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnParticleUpdateJobScheduledAsync() + { + return ((IAsyncOnParticleUpdateJobScheduledHandler)new AsyncTriggerHandler(this, true)).OnParticleUpdateJobScheduledAsync(); + } + + public UniTask OnParticleUpdateJobScheduledAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnParticleUpdateJobScheduledHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnParticleUpdateJobScheduledAsync(); + } + } +#endif +#endregion + +#region PostRender + + public interface IAsyncOnPostRenderHandler + { + UniTask OnPostRenderAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPostRenderHandler + { + UniTask IAsyncOnPostRenderHandler.OnPostRenderAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPostRenderTrigger GetAsyncPostRenderTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPostRenderTrigger GetAsyncPostRenderTrigger(this Component component) + { + return component.gameObject.GetAsyncPostRenderTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPostRenderTrigger : AsyncTriggerBase + { + void OnPostRender() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnPostRenderHandler GetOnPostRenderAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPostRenderHandler GetOnPostRenderAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPostRenderAsync() + { + return ((IAsyncOnPostRenderHandler)new AsyncTriggerHandler(this, true)).OnPostRenderAsync(); + } + + public UniTask OnPostRenderAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPostRenderHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPostRenderAsync(); + } + } +#endregion + +#region PreCull + + public interface IAsyncOnPreCullHandler + { + UniTask OnPreCullAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPreCullHandler + { + UniTask IAsyncOnPreCullHandler.OnPreCullAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPreCullTrigger GetAsyncPreCullTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPreCullTrigger GetAsyncPreCullTrigger(this Component component) + { + return component.gameObject.GetAsyncPreCullTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPreCullTrigger : AsyncTriggerBase + { + void OnPreCull() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnPreCullHandler GetOnPreCullAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPreCullHandler GetOnPreCullAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPreCullAsync() + { + return ((IAsyncOnPreCullHandler)new AsyncTriggerHandler(this, true)).OnPreCullAsync(); + } + + public UniTask OnPreCullAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPreCullHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPreCullAsync(); + } + } +#endregion + +#region PreRender + + public interface IAsyncOnPreRenderHandler + { + UniTask OnPreRenderAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPreRenderHandler + { + UniTask IAsyncOnPreRenderHandler.OnPreRenderAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPreRenderTrigger GetAsyncPreRenderTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPreRenderTrigger GetAsyncPreRenderTrigger(this Component component) + { + return component.gameObject.GetAsyncPreRenderTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPreRenderTrigger : AsyncTriggerBase + { + void OnPreRender() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnPreRenderHandler GetOnPreRenderAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPreRenderHandler GetOnPreRenderAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPreRenderAsync() + { + return ((IAsyncOnPreRenderHandler)new AsyncTriggerHandler(this, true)).OnPreRenderAsync(); + } + + public UniTask OnPreRenderAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPreRenderHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPreRenderAsync(); + } + } +#endregion + +#region RectTransformDimensionsChange + + public interface IAsyncOnRectTransformDimensionsChangeHandler + { + UniTask OnRectTransformDimensionsChangeAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnRectTransformDimensionsChangeHandler + { + UniTask IAsyncOnRectTransformDimensionsChangeHandler.OnRectTransformDimensionsChangeAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncRectTransformDimensionsChangeTrigger GetAsyncRectTransformDimensionsChangeTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncRectTransformDimensionsChangeTrigger GetAsyncRectTransformDimensionsChangeTrigger(this Component component) + { + return component.gameObject.GetAsyncRectTransformDimensionsChangeTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncRectTransformDimensionsChangeTrigger : AsyncTriggerBase + { + void OnRectTransformDimensionsChange() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnRectTransformDimensionsChangeHandler GetOnRectTransformDimensionsChangeAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnRectTransformDimensionsChangeHandler GetOnRectTransformDimensionsChangeAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnRectTransformDimensionsChangeAsync() + { + return ((IAsyncOnRectTransformDimensionsChangeHandler)new AsyncTriggerHandler(this, true)).OnRectTransformDimensionsChangeAsync(); + } + + public UniTask OnRectTransformDimensionsChangeAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnRectTransformDimensionsChangeHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnRectTransformDimensionsChangeAsync(); + } + } +#endregion + +#region RectTransformRemoved + + public interface IAsyncOnRectTransformRemovedHandler + { + UniTask OnRectTransformRemovedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnRectTransformRemovedHandler + { + UniTask IAsyncOnRectTransformRemovedHandler.OnRectTransformRemovedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncRectTransformRemovedTrigger GetAsyncRectTransformRemovedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncRectTransformRemovedTrigger GetAsyncRectTransformRemovedTrigger(this Component component) + { + return component.gameObject.GetAsyncRectTransformRemovedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncRectTransformRemovedTrigger : AsyncTriggerBase + { + void OnRectTransformRemoved() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnRectTransformRemovedHandler GetOnRectTransformRemovedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnRectTransformRemovedHandler GetOnRectTransformRemovedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnRectTransformRemovedAsync() + { + return ((IAsyncOnRectTransformRemovedHandler)new AsyncTriggerHandler(this, true)).OnRectTransformRemovedAsync(); + } + + public UniTask OnRectTransformRemovedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnRectTransformRemovedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnRectTransformRemovedAsync(); + } + } +#endregion + +#region RenderImage + + public interface IAsyncOnRenderImageHandler + { + UniTask<(RenderTexture source, RenderTexture destination)> OnRenderImageAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnRenderImageHandler + { + UniTask<(RenderTexture source, RenderTexture destination)> IAsyncOnRenderImageHandler.OnRenderImageAsync() + { + core.Reset(); + return new UniTask<(RenderTexture source, RenderTexture destination)>((IUniTaskSource<(RenderTexture source, RenderTexture destination)>)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncRenderImageTrigger GetAsyncRenderImageTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncRenderImageTrigger GetAsyncRenderImageTrigger(this Component component) + { + return component.gameObject.GetAsyncRenderImageTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncRenderImageTrigger : AsyncTriggerBase<(RenderTexture source, RenderTexture destination)> + { + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + RaiseEvent((source, destination)); + } + + public IAsyncOnRenderImageHandler GetOnRenderImageAsyncHandler() + { + return new AsyncTriggerHandler<(RenderTexture source, RenderTexture destination)>(this, false); + } + + public IAsyncOnRenderImageHandler GetOnRenderImageAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler<(RenderTexture source, RenderTexture destination)>(this, cancellationToken, false); + } + + public UniTask<(RenderTexture source, RenderTexture destination)> OnRenderImageAsync() + { + return ((IAsyncOnRenderImageHandler)new AsyncTriggerHandler<(RenderTexture source, RenderTexture destination)>(this, true)).OnRenderImageAsync(); + } + + public UniTask<(RenderTexture source, RenderTexture destination)> OnRenderImageAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnRenderImageHandler)new AsyncTriggerHandler<(RenderTexture source, RenderTexture destination)>(this, cancellationToken, true)).OnRenderImageAsync(); + } + } +#endregion + +#region RenderObject + + public interface IAsyncOnRenderObjectHandler + { + UniTask OnRenderObjectAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnRenderObjectHandler + { + UniTask IAsyncOnRenderObjectHandler.OnRenderObjectAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncRenderObjectTrigger GetAsyncRenderObjectTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncRenderObjectTrigger GetAsyncRenderObjectTrigger(this Component component) + { + return component.gameObject.GetAsyncRenderObjectTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncRenderObjectTrigger : AsyncTriggerBase + { + void OnRenderObject() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnRenderObjectHandler GetOnRenderObjectAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnRenderObjectHandler GetOnRenderObjectAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnRenderObjectAsync() + { + return ((IAsyncOnRenderObjectHandler)new AsyncTriggerHandler(this, true)).OnRenderObjectAsync(); + } + + public UniTask OnRenderObjectAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnRenderObjectHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnRenderObjectAsync(); + } + } +#endregion + +#region ServerInitialized + + public interface IAsyncOnServerInitializedHandler + { + UniTask OnServerInitializedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnServerInitializedHandler + { + UniTask IAsyncOnServerInitializedHandler.OnServerInitializedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncServerInitializedTrigger GetAsyncServerInitializedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncServerInitializedTrigger GetAsyncServerInitializedTrigger(this Component component) + { + return component.gameObject.GetAsyncServerInitializedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncServerInitializedTrigger : AsyncTriggerBase + { + void OnServerInitialized() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnServerInitializedHandler GetOnServerInitializedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnServerInitializedHandler GetOnServerInitializedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnServerInitializedAsync() + { + return ((IAsyncOnServerInitializedHandler)new AsyncTriggerHandler(this, true)).OnServerInitializedAsync(); + } + + public UniTask OnServerInitializedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnServerInitializedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnServerInitializedAsync(); + } + } +#endregion + +#region TransformChildrenChanged + + public interface IAsyncOnTransformChildrenChangedHandler + { + UniTask OnTransformChildrenChangedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTransformChildrenChangedHandler + { + UniTask IAsyncOnTransformChildrenChangedHandler.OnTransformChildrenChangedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTransformChildrenChangedTrigger GetAsyncTransformChildrenChangedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTransformChildrenChangedTrigger GetAsyncTransformChildrenChangedTrigger(this Component component) + { + return component.gameObject.GetAsyncTransformChildrenChangedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTransformChildrenChangedTrigger : AsyncTriggerBase + { + void OnTransformChildrenChanged() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnTransformChildrenChangedHandler GetOnTransformChildrenChangedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTransformChildrenChangedHandler GetOnTransformChildrenChangedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTransformChildrenChangedAsync() + { + return ((IAsyncOnTransformChildrenChangedHandler)new AsyncTriggerHandler(this, true)).OnTransformChildrenChangedAsync(); + } + + public UniTask OnTransformChildrenChangedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTransformChildrenChangedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTransformChildrenChangedAsync(); + } + } +#endregion + +#region TransformParentChanged + + public interface IAsyncOnTransformParentChangedHandler + { + UniTask OnTransformParentChangedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTransformParentChangedHandler + { + UniTask IAsyncOnTransformParentChangedHandler.OnTransformParentChangedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTransformParentChangedTrigger GetAsyncTransformParentChangedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTransformParentChangedTrigger GetAsyncTransformParentChangedTrigger(this Component component) + { + return component.gameObject.GetAsyncTransformParentChangedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTransformParentChangedTrigger : AsyncTriggerBase + { + void OnTransformParentChanged() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnTransformParentChangedHandler GetOnTransformParentChangedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTransformParentChangedHandler GetOnTransformParentChangedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTransformParentChangedAsync() + { + return ((IAsyncOnTransformParentChangedHandler)new AsyncTriggerHandler(this, true)).OnTransformParentChangedAsync(); + } + + public UniTask OnTransformParentChangedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTransformParentChangedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTransformParentChangedAsync(); + } + } +#endregion + +#region TriggerEnter +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnTriggerEnterHandler + { + UniTask OnTriggerEnterAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTriggerEnterHandler + { + UniTask IAsyncOnTriggerEnterHandler.OnTriggerEnterAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTriggerEnterTrigger GetAsyncTriggerEnterTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTriggerEnterTrigger GetAsyncTriggerEnterTrigger(this Component component) + { + return component.gameObject.GetAsyncTriggerEnterTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTriggerEnterTrigger : AsyncTriggerBase + { + void OnTriggerEnter(Collider other) + { + RaiseEvent((other)); + } + + public IAsyncOnTriggerEnterHandler GetOnTriggerEnterAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTriggerEnterHandler GetOnTriggerEnterAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTriggerEnterAsync() + { + return ((IAsyncOnTriggerEnterHandler)new AsyncTriggerHandler(this, true)).OnTriggerEnterAsync(); + } + + public UniTask OnTriggerEnterAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTriggerEnterHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTriggerEnterAsync(); + } + } +#endif +#endregion + +#region TriggerEnter2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnTriggerEnter2DHandler + { + UniTask OnTriggerEnter2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTriggerEnter2DHandler + { + UniTask IAsyncOnTriggerEnter2DHandler.OnTriggerEnter2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTriggerEnter2DTrigger GetAsyncTriggerEnter2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTriggerEnter2DTrigger GetAsyncTriggerEnter2DTrigger(this Component component) + { + return component.gameObject.GetAsyncTriggerEnter2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTriggerEnter2DTrigger : AsyncTriggerBase + { + void OnTriggerEnter2D(Collider2D other) + { + RaiseEvent((other)); + } + + public IAsyncOnTriggerEnter2DHandler GetOnTriggerEnter2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTriggerEnter2DHandler GetOnTriggerEnter2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTriggerEnter2DAsync() + { + return ((IAsyncOnTriggerEnter2DHandler)new AsyncTriggerHandler(this, true)).OnTriggerEnter2DAsync(); + } + + public UniTask OnTriggerEnter2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTriggerEnter2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTriggerEnter2DAsync(); + } + } +#endif +#endregion + +#region TriggerExit +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnTriggerExitHandler + { + UniTask OnTriggerExitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTriggerExitHandler + { + UniTask IAsyncOnTriggerExitHandler.OnTriggerExitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTriggerExitTrigger GetAsyncTriggerExitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTriggerExitTrigger GetAsyncTriggerExitTrigger(this Component component) + { + return component.gameObject.GetAsyncTriggerExitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTriggerExitTrigger : AsyncTriggerBase + { + void OnTriggerExit(Collider other) + { + RaiseEvent((other)); + } + + public IAsyncOnTriggerExitHandler GetOnTriggerExitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTriggerExitHandler GetOnTriggerExitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTriggerExitAsync() + { + return ((IAsyncOnTriggerExitHandler)new AsyncTriggerHandler(this, true)).OnTriggerExitAsync(); + } + + public UniTask OnTriggerExitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTriggerExitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTriggerExitAsync(); + } + } +#endif +#endregion + +#region TriggerExit2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnTriggerExit2DHandler + { + UniTask OnTriggerExit2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTriggerExit2DHandler + { + UniTask IAsyncOnTriggerExit2DHandler.OnTriggerExit2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTriggerExit2DTrigger GetAsyncTriggerExit2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTriggerExit2DTrigger GetAsyncTriggerExit2DTrigger(this Component component) + { + return component.gameObject.GetAsyncTriggerExit2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTriggerExit2DTrigger : AsyncTriggerBase + { + void OnTriggerExit2D(Collider2D other) + { + RaiseEvent((other)); + } + + public IAsyncOnTriggerExit2DHandler GetOnTriggerExit2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTriggerExit2DHandler GetOnTriggerExit2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTriggerExit2DAsync() + { + return ((IAsyncOnTriggerExit2DHandler)new AsyncTriggerHandler(this, true)).OnTriggerExit2DAsync(); + } + + public UniTask OnTriggerExit2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTriggerExit2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTriggerExit2DAsync(); + } + } +#endif +#endregion + +#region TriggerStay +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS_SUPPORT + + public interface IAsyncOnTriggerStayHandler + { + UniTask OnTriggerStayAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTriggerStayHandler + { + UniTask IAsyncOnTriggerStayHandler.OnTriggerStayAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTriggerStayTrigger GetAsyncTriggerStayTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTriggerStayTrigger GetAsyncTriggerStayTrigger(this Component component) + { + return component.gameObject.GetAsyncTriggerStayTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTriggerStayTrigger : AsyncTriggerBase + { + void OnTriggerStay(Collider other) + { + RaiseEvent((other)); + } + + public IAsyncOnTriggerStayHandler GetOnTriggerStayAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTriggerStayHandler GetOnTriggerStayAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTriggerStayAsync() + { + return ((IAsyncOnTriggerStayHandler)new AsyncTriggerHandler(this, true)).OnTriggerStayAsync(); + } + + public UniTask OnTriggerStayAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTriggerStayHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTriggerStayAsync(); + } + } +#endif +#endregion + +#region TriggerStay2D +#if !UNITY_2019_1_OR_NEWER || UNITASK_PHYSICS2D_SUPPORT + + public interface IAsyncOnTriggerStay2DHandler + { + UniTask OnTriggerStay2DAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnTriggerStay2DHandler + { + UniTask IAsyncOnTriggerStay2DHandler.OnTriggerStay2DAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncTriggerStay2DTrigger GetAsyncTriggerStay2DTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncTriggerStay2DTrigger GetAsyncTriggerStay2DTrigger(this Component component) + { + return component.gameObject.GetAsyncTriggerStay2DTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncTriggerStay2DTrigger : AsyncTriggerBase + { + void OnTriggerStay2D(Collider2D other) + { + RaiseEvent((other)); + } + + public IAsyncOnTriggerStay2DHandler GetOnTriggerStay2DAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnTriggerStay2DHandler GetOnTriggerStay2DAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnTriggerStay2DAsync() + { + return ((IAsyncOnTriggerStay2DHandler)new AsyncTriggerHandler(this, true)).OnTriggerStay2DAsync(); + } + + public UniTask OnTriggerStay2DAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnTriggerStay2DHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnTriggerStay2DAsync(); + } + } +#endif +#endregion + +#region Validate + + public interface IAsyncOnValidateHandler + { + UniTask OnValidateAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnValidateHandler + { + UniTask IAsyncOnValidateHandler.OnValidateAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncValidateTrigger GetAsyncValidateTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncValidateTrigger GetAsyncValidateTrigger(this Component component) + { + return component.gameObject.GetAsyncValidateTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncValidateTrigger : AsyncTriggerBase + { + void OnValidate() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnValidateHandler GetOnValidateAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnValidateHandler GetOnValidateAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnValidateAsync() + { + return ((IAsyncOnValidateHandler)new AsyncTriggerHandler(this, true)).OnValidateAsync(); + } + + public UniTask OnValidateAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnValidateHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnValidateAsync(); + } + } +#endregion + +#region WillRenderObject + + public interface IAsyncOnWillRenderObjectHandler + { + UniTask OnWillRenderObjectAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnWillRenderObjectHandler + { + UniTask IAsyncOnWillRenderObjectHandler.OnWillRenderObjectAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncWillRenderObjectTrigger GetAsyncWillRenderObjectTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncWillRenderObjectTrigger GetAsyncWillRenderObjectTrigger(this Component component) + { + return component.gameObject.GetAsyncWillRenderObjectTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncWillRenderObjectTrigger : AsyncTriggerBase + { + void OnWillRenderObject() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncOnWillRenderObjectHandler GetOnWillRenderObjectAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnWillRenderObjectHandler GetOnWillRenderObjectAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnWillRenderObjectAsync() + { + return ((IAsyncOnWillRenderObjectHandler)new AsyncTriggerHandler(this, true)).OnWillRenderObjectAsync(); + } + + public UniTask OnWillRenderObjectAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnWillRenderObjectHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnWillRenderObjectAsync(); + } + } +#endregion + +#region Reset + + public interface IAsyncResetHandler + { + UniTask ResetAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncResetHandler + { + UniTask IAsyncResetHandler.ResetAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncResetTrigger GetAsyncResetTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncResetTrigger GetAsyncResetTrigger(this Component component) + { + return component.gameObject.GetAsyncResetTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncResetTrigger : AsyncTriggerBase + { + void Reset() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncResetHandler GetResetAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncResetHandler GetResetAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask ResetAsync() + { + return ((IAsyncResetHandler)new AsyncTriggerHandler(this, true)).ResetAsync(); + } + + public UniTask ResetAsync(CancellationToken cancellationToken) + { + return ((IAsyncResetHandler)new AsyncTriggerHandler(this, cancellationToken, true)).ResetAsync(); + } + } +#endregion + +#region Update + + public interface IAsyncUpdateHandler + { + UniTask UpdateAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncUpdateHandler + { + UniTask IAsyncUpdateHandler.UpdateAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncUpdateTrigger GetAsyncUpdateTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncUpdateTrigger GetAsyncUpdateTrigger(this Component component) + { + return component.gameObject.GetAsyncUpdateTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncUpdateTrigger : AsyncTriggerBase + { + void Update() + { + RaiseEvent(AsyncUnit.Default); + } + + public IAsyncUpdateHandler GetUpdateAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncUpdateHandler GetUpdateAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask UpdateAsync() + { + return ((IAsyncUpdateHandler)new AsyncTriggerHandler(this, true)).UpdateAsync(); + } + + public UniTask UpdateAsync(CancellationToken cancellationToken) + { + return ((IAsyncUpdateHandler)new AsyncTriggerHandler(this, cancellationToken, true)).UpdateAsync(); + } + } +#endregion + +#region BeginDrag +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnBeginDragHandler + { + UniTask OnBeginDragAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnBeginDragHandler + { + UniTask IAsyncOnBeginDragHandler.OnBeginDragAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncBeginDragTrigger GetAsyncBeginDragTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncBeginDragTrigger GetAsyncBeginDragTrigger(this Component component) + { + return component.gameObject.GetAsyncBeginDragTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncBeginDragTrigger : AsyncTriggerBase, IBeginDragHandler + { + void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnBeginDragHandler GetOnBeginDragAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnBeginDragHandler GetOnBeginDragAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnBeginDragAsync() + { + return ((IAsyncOnBeginDragHandler)new AsyncTriggerHandler(this, true)).OnBeginDragAsync(); + } + + public UniTask OnBeginDragAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnBeginDragHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnBeginDragAsync(); + } + } +#endif +#endregion + +#region Cancel +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnCancelHandler + { + UniTask OnCancelAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnCancelHandler + { + UniTask IAsyncOnCancelHandler.OnCancelAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncCancelTrigger GetAsyncCancelTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncCancelTrigger GetAsyncCancelTrigger(this Component component) + { + return component.gameObject.GetAsyncCancelTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncCancelTrigger : AsyncTriggerBase, ICancelHandler + { + void ICancelHandler.OnCancel(BaseEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnCancelHandler GetOnCancelAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnCancelHandler GetOnCancelAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnCancelAsync() + { + return ((IAsyncOnCancelHandler)new AsyncTriggerHandler(this, true)).OnCancelAsync(); + } + + public UniTask OnCancelAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnCancelHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnCancelAsync(); + } + } +#endif +#endregion + +#region Deselect +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnDeselectHandler + { + UniTask OnDeselectAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnDeselectHandler + { + UniTask IAsyncOnDeselectHandler.OnDeselectAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncDeselectTrigger GetAsyncDeselectTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDeselectTrigger GetAsyncDeselectTrigger(this Component component) + { + return component.gameObject.GetAsyncDeselectTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDeselectTrigger : AsyncTriggerBase, IDeselectHandler + { + void IDeselectHandler.OnDeselect(BaseEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnDeselectHandler GetOnDeselectAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnDeselectHandler GetOnDeselectAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnDeselectAsync() + { + return ((IAsyncOnDeselectHandler)new AsyncTriggerHandler(this, true)).OnDeselectAsync(); + } + + public UniTask OnDeselectAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnDeselectHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnDeselectAsync(); + } + } +#endif +#endregion + +#region Drag +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnDragHandler + { + UniTask OnDragAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnDragHandler + { + UniTask IAsyncOnDragHandler.OnDragAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncDragTrigger GetAsyncDragTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDragTrigger GetAsyncDragTrigger(this Component component) + { + return component.gameObject.GetAsyncDragTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDragTrigger : AsyncTriggerBase, IDragHandler + { + void IDragHandler.OnDrag(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnDragHandler GetOnDragAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnDragHandler GetOnDragAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnDragAsync() + { + return ((IAsyncOnDragHandler)new AsyncTriggerHandler(this, true)).OnDragAsync(); + } + + public UniTask OnDragAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnDragHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnDragAsync(); + } + } +#endif +#endregion + +#region Drop +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnDropHandler + { + UniTask OnDropAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnDropHandler + { + UniTask IAsyncOnDropHandler.OnDropAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncDropTrigger GetAsyncDropTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncDropTrigger GetAsyncDropTrigger(this Component component) + { + return component.gameObject.GetAsyncDropTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncDropTrigger : AsyncTriggerBase, IDropHandler + { + void IDropHandler.OnDrop(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnDropHandler GetOnDropAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnDropHandler GetOnDropAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnDropAsync() + { + return ((IAsyncOnDropHandler)new AsyncTriggerHandler(this, true)).OnDropAsync(); + } + + public UniTask OnDropAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnDropHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnDropAsync(); + } + } +#endif +#endregion + +#region EndDrag +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnEndDragHandler + { + UniTask OnEndDragAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnEndDragHandler + { + UniTask IAsyncOnEndDragHandler.OnEndDragAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncEndDragTrigger GetAsyncEndDragTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncEndDragTrigger GetAsyncEndDragTrigger(this Component component) + { + return component.gameObject.GetAsyncEndDragTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncEndDragTrigger : AsyncTriggerBase, IEndDragHandler + { + void IEndDragHandler.OnEndDrag(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnEndDragHandler GetOnEndDragAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnEndDragHandler GetOnEndDragAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnEndDragAsync() + { + return ((IAsyncOnEndDragHandler)new AsyncTriggerHandler(this, true)).OnEndDragAsync(); + } + + public UniTask OnEndDragAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnEndDragHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnEndDragAsync(); + } + } +#endif +#endregion + +#region InitializePotentialDrag +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnInitializePotentialDragHandler + { + UniTask OnInitializePotentialDragAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnInitializePotentialDragHandler + { + UniTask IAsyncOnInitializePotentialDragHandler.OnInitializePotentialDragAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncInitializePotentialDragTrigger GetAsyncInitializePotentialDragTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncInitializePotentialDragTrigger GetAsyncInitializePotentialDragTrigger(this Component component) + { + return component.gameObject.GetAsyncInitializePotentialDragTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncInitializePotentialDragTrigger : AsyncTriggerBase, IInitializePotentialDragHandler + { + void IInitializePotentialDragHandler.OnInitializePotentialDrag(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnInitializePotentialDragHandler GetOnInitializePotentialDragAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnInitializePotentialDragHandler GetOnInitializePotentialDragAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnInitializePotentialDragAsync() + { + return ((IAsyncOnInitializePotentialDragHandler)new AsyncTriggerHandler(this, true)).OnInitializePotentialDragAsync(); + } + + public UniTask OnInitializePotentialDragAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnInitializePotentialDragHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnInitializePotentialDragAsync(); + } + } +#endif +#endregion + +#region Move +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnMoveHandler + { + UniTask OnMoveAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnMoveHandler + { + UniTask IAsyncOnMoveHandler.OnMoveAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncMoveTrigger GetAsyncMoveTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncMoveTrigger GetAsyncMoveTrigger(this Component component) + { + return component.gameObject.GetAsyncMoveTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncMoveTrigger : AsyncTriggerBase, IMoveHandler + { + void IMoveHandler.OnMove(AxisEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnMoveHandler GetOnMoveAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnMoveHandler GetOnMoveAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnMoveAsync() + { + return ((IAsyncOnMoveHandler)new AsyncTriggerHandler(this, true)).OnMoveAsync(); + } + + public UniTask OnMoveAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnMoveHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnMoveAsync(); + } + } +#endif +#endregion + +#region PointerClick +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnPointerClickHandler + { + UniTask OnPointerClickAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPointerClickHandler + { + UniTask IAsyncOnPointerClickHandler.OnPointerClickAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPointerClickTrigger GetAsyncPointerClickTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPointerClickTrigger GetAsyncPointerClickTrigger(this Component component) + { + return component.gameObject.GetAsyncPointerClickTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPointerClickTrigger : AsyncTriggerBase, IPointerClickHandler + { + void IPointerClickHandler.OnPointerClick(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnPointerClickHandler GetOnPointerClickAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPointerClickHandler GetOnPointerClickAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPointerClickAsync() + { + return ((IAsyncOnPointerClickHandler)new AsyncTriggerHandler(this, true)).OnPointerClickAsync(); + } + + public UniTask OnPointerClickAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPointerClickHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPointerClickAsync(); + } + } +#endif +#endregion + +#region PointerDown +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnPointerDownHandler + { + UniTask OnPointerDownAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPointerDownHandler + { + UniTask IAsyncOnPointerDownHandler.OnPointerDownAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPointerDownTrigger GetAsyncPointerDownTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPointerDownTrigger GetAsyncPointerDownTrigger(this Component component) + { + return component.gameObject.GetAsyncPointerDownTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPointerDownTrigger : AsyncTriggerBase, IPointerDownHandler + { + void IPointerDownHandler.OnPointerDown(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnPointerDownHandler GetOnPointerDownAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPointerDownHandler GetOnPointerDownAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPointerDownAsync() + { + return ((IAsyncOnPointerDownHandler)new AsyncTriggerHandler(this, true)).OnPointerDownAsync(); + } + + public UniTask OnPointerDownAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPointerDownHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPointerDownAsync(); + } + } +#endif +#endregion + +#region PointerEnter +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnPointerEnterHandler + { + UniTask OnPointerEnterAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPointerEnterHandler + { + UniTask IAsyncOnPointerEnterHandler.OnPointerEnterAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPointerEnterTrigger GetAsyncPointerEnterTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPointerEnterTrigger GetAsyncPointerEnterTrigger(this Component component) + { + return component.gameObject.GetAsyncPointerEnterTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPointerEnterTrigger : AsyncTriggerBase, IPointerEnterHandler + { + void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnPointerEnterHandler GetOnPointerEnterAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPointerEnterHandler GetOnPointerEnterAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPointerEnterAsync() + { + return ((IAsyncOnPointerEnterHandler)new AsyncTriggerHandler(this, true)).OnPointerEnterAsync(); + } + + public UniTask OnPointerEnterAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPointerEnterHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPointerEnterAsync(); + } + } +#endif +#endregion + +#region PointerExit +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnPointerExitHandler + { + UniTask OnPointerExitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPointerExitHandler + { + UniTask IAsyncOnPointerExitHandler.OnPointerExitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPointerExitTrigger GetAsyncPointerExitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPointerExitTrigger GetAsyncPointerExitTrigger(this Component component) + { + return component.gameObject.GetAsyncPointerExitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPointerExitTrigger : AsyncTriggerBase, IPointerExitHandler + { + void IPointerExitHandler.OnPointerExit(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnPointerExitHandler GetOnPointerExitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPointerExitHandler GetOnPointerExitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPointerExitAsync() + { + return ((IAsyncOnPointerExitHandler)new AsyncTriggerHandler(this, true)).OnPointerExitAsync(); + } + + public UniTask OnPointerExitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPointerExitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPointerExitAsync(); + } + } +#endif +#endregion + +#region PointerUp +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnPointerUpHandler + { + UniTask OnPointerUpAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnPointerUpHandler + { + UniTask IAsyncOnPointerUpHandler.OnPointerUpAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncPointerUpTrigger GetAsyncPointerUpTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncPointerUpTrigger GetAsyncPointerUpTrigger(this Component component) + { + return component.gameObject.GetAsyncPointerUpTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncPointerUpTrigger : AsyncTriggerBase, IPointerUpHandler + { + void IPointerUpHandler.OnPointerUp(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnPointerUpHandler GetOnPointerUpAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnPointerUpHandler GetOnPointerUpAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnPointerUpAsync() + { + return ((IAsyncOnPointerUpHandler)new AsyncTriggerHandler(this, true)).OnPointerUpAsync(); + } + + public UniTask OnPointerUpAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnPointerUpHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnPointerUpAsync(); + } + } +#endif +#endregion + +#region Scroll +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnScrollHandler + { + UniTask OnScrollAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnScrollHandler + { + UniTask IAsyncOnScrollHandler.OnScrollAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncScrollTrigger GetAsyncScrollTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncScrollTrigger GetAsyncScrollTrigger(this Component component) + { + return component.gameObject.GetAsyncScrollTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncScrollTrigger : AsyncTriggerBase, IScrollHandler + { + void IScrollHandler.OnScroll(PointerEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnScrollHandler GetOnScrollAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnScrollHandler GetOnScrollAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnScrollAsync() + { + return ((IAsyncOnScrollHandler)new AsyncTriggerHandler(this, true)).OnScrollAsync(); + } + + public UniTask OnScrollAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnScrollHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnScrollAsync(); + } + } +#endif +#endregion + +#region Select +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnSelectHandler + { + UniTask OnSelectAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnSelectHandler + { + UniTask IAsyncOnSelectHandler.OnSelectAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncSelectTrigger GetAsyncSelectTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncSelectTrigger GetAsyncSelectTrigger(this Component component) + { + return component.gameObject.GetAsyncSelectTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncSelectTrigger : AsyncTriggerBase, ISelectHandler + { + void ISelectHandler.OnSelect(BaseEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnSelectHandler GetOnSelectAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnSelectHandler GetOnSelectAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnSelectAsync() + { + return ((IAsyncOnSelectHandler)new AsyncTriggerHandler(this, true)).OnSelectAsync(); + } + + public UniTask OnSelectAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnSelectHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnSelectAsync(); + } + } +#endif +#endregion + +#region Submit +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnSubmitHandler + { + UniTask OnSubmitAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnSubmitHandler + { + UniTask IAsyncOnSubmitHandler.OnSubmitAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncSubmitTrigger GetAsyncSubmitTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncSubmitTrigger GetAsyncSubmitTrigger(this Component component) + { + return component.gameObject.GetAsyncSubmitTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncSubmitTrigger : AsyncTriggerBase, ISubmitHandler + { + void ISubmitHandler.OnSubmit(BaseEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnSubmitHandler GetOnSubmitAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnSubmitHandler GetOnSubmitAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnSubmitAsync() + { + return ((IAsyncOnSubmitHandler)new AsyncTriggerHandler(this, true)).OnSubmitAsync(); + } + + public UniTask OnSubmitAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnSubmitHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnSubmitAsync(); + } + } +#endif +#endregion + +#region UpdateSelected +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + + public interface IAsyncOnUpdateSelectedHandler + { + UniTask OnUpdateSelectedAsync(); + } + + public partial class AsyncTriggerHandler : IAsyncOnUpdateSelectedHandler + { + UniTask IAsyncOnUpdateSelectedHandler.OnUpdateSelectedAsync() + { + core.Reset(); + return new UniTask((IUniTaskSource)(object)this, core.Version); + } + } + + public static partial class AsyncTriggerExtensions + { + public static AsyncUpdateSelectedTrigger GetAsyncUpdateSelectedTrigger(this GameObject gameObject) + { + return GetOrAddComponent(gameObject); + } + + public static AsyncUpdateSelectedTrigger GetAsyncUpdateSelectedTrigger(this Component component) + { + return component.gameObject.GetAsyncUpdateSelectedTrigger(); + } + } + + [DisallowMultipleComponent] + public sealed class AsyncUpdateSelectedTrigger : AsyncTriggerBase, IUpdateSelectedHandler + { + void IUpdateSelectedHandler.OnUpdateSelected(BaseEventData eventData) + { + RaiseEvent((eventData)); + } + + public IAsyncOnUpdateSelectedHandler GetOnUpdateSelectedAsyncHandler() + { + return new AsyncTriggerHandler(this, false); + } + + public IAsyncOnUpdateSelectedHandler GetOnUpdateSelectedAsyncHandler(CancellationToken cancellationToken) + { + return new AsyncTriggerHandler(this, cancellationToken, false); + } + + public UniTask OnUpdateSelectedAsync() + { + return ((IAsyncOnUpdateSelectedHandler)new AsyncTriggerHandler(this, true)).OnUpdateSelectedAsync(); + } + + public UniTask OnUpdateSelectedAsync(CancellationToken cancellationToken) + { + return ((IAsyncOnUpdateSelectedHandler)new AsyncTriggerHandler(this, cancellationToken, true)).OnUpdateSelectedAsync(); + } + } +#endif +#endregion + +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs.meta new file mode 100644 index 00000000..82aa6792 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c30655636c35c3d4da44064af3d2d9a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.AsValueTask.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.AsValueTask.cs new file mode 100644 index 00000000..ab1e913f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.AsValueTask.cs @@ -0,0 +1,104 @@ +#pragma warning disable 0649 + +#if UNITASK_NETCORE || UNITY_2022_3_OR_NEWER +#define SUPPORT_VALUETASK +#endif + +#if SUPPORT_VALUETASK + +using System; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; + +namespace Cysharp.Threading.Tasks +{ + public static class UniTaskValueTaskExtensions + { + public static ValueTask AsValueTask(this in UniTask task) + { +#if (UNITASK_NETCORE && NETSTANDARD2_0) + return new ValueTask(new UniTaskValueTaskSource(task), 0); +#else + return task; +#endif + } + + public static ValueTask AsValueTask(this in UniTask task) + { +#if (UNITASK_NETCORE && NETSTANDARD2_0) + return new ValueTask(new UniTaskValueTaskSource(task), 0); +#else + return task; +#endif + } + + public static async UniTask AsUniTask(this ValueTask task) + { + return await task; + } + + public static async UniTask AsUniTask(this ValueTask task) + { + await task; + } + +#if (UNITASK_NETCORE && NETSTANDARD2_0) + + class UniTaskValueTaskSource : IValueTaskSource + { + readonly UniTask task; + readonly UniTask.Awaiter awaiter; + + public UniTaskValueTaskSource(UniTask task) + { + this.task = task; + this.awaiter = task.GetAwaiter(); + } + + public void GetResult(short token) + { + awaiter.GetResult(); + } + + public ValueTaskSourceStatus GetStatus(short token) + { + return (ValueTaskSourceStatus)task.Status; + } + + public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) + { + awaiter.SourceOnCompleted(continuation, state); + } + } + + class UniTaskValueTaskSource : IValueTaskSource + { + readonly UniTask task; + readonly UniTask.Awaiter awaiter; + + public UniTaskValueTaskSource(UniTask task) + { + this.task = task; + this.awaiter = task.GetAwaiter(); + } + + public T GetResult(short token) + { + return awaiter.GetResult(); + } + + public ValueTaskSourceStatus GetStatus(short token) + { + return (ValueTaskSourceStatus)task.Status; + } + + public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) + { + awaiter.SourceOnCompleted(continuation, state); + } + } + +#endif + } +} +#endif diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.AsValueTask.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.AsValueTask.cs.meta new file mode 100644 index 00000000..801bce1c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.AsValueTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d38f0478933be42d895c37b862540a1c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Bridge.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Bridge.cs new file mode 100644 index 00000000..c9042999 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Bridge.cs @@ -0,0 +1,18 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections; + +namespace Cysharp.Threading.Tasks +{ + // UnityEngine Bridges. + + public partial struct UniTask + { + public static IEnumerator ToCoroutine(Func taskFactory) + { + return taskFactory().ToCoroutine(); + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Bridge.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Bridge.cs.meta new file mode 100644 index 00000000..6f8da804 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Bridge.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd6beac8e0ebd264e9ba246c39429c72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Delay.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Delay.cs new file mode 100644 index 00000000..4ff699dd --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Delay.cs @@ -0,0 +1,1132 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks +{ + public enum DelayType + { + /// use Time.deltaTime. + DeltaTime, + /// Ignore timescale, use Time.unscaledDeltaTime. + UnscaledDeltaTime, + /// use Stopwatch.GetTimestamp(). + Realtime + } + + public partial struct UniTask + { + public static YieldAwaitable Yield() + { + // optimized for single continuation + return new YieldAwaitable(PlayerLoopTiming.Update); + } + + public static YieldAwaitable Yield(PlayerLoopTiming timing) + { + // optimized for single continuation + return new YieldAwaitable(timing); + } + + public static UniTask Yield(CancellationToken cancellationToken, bool cancelImmediately = false) + { + return new UniTask(YieldPromise.Create(PlayerLoopTiming.Update, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask Yield(PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately = false) + { + return new UniTask(YieldPromise.Create(timing, cancellationToken, cancelImmediately, out var token), token); + } + + /// + /// Similar as UniTask.Yield but guaranteed run on next frame. + /// + public static UniTask NextFrame() + { + return new UniTask(NextFramePromise.Create(PlayerLoopTiming.Update, CancellationToken.None, false, out var token), token); + } + + /// + /// Similar as UniTask.Yield but guaranteed run on next frame. + /// + public static UniTask NextFrame(PlayerLoopTiming timing) + { + return new UniTask(NextFramePromise.Create(timing, CancellationToken.None, false, out var token), token); + } + + /// + /// Similar as UniTask.Yield but guaranteed run on next frame. + /// + public static UniTask NextFrame(CancellationToken cancellationToken, bool cancelImmediately = false) + { + return new UniTask(NextFramePromise.Create(PlayerLoopTiming.Update, cancellationToken, cancelImmediately, out var token), token); + } + + /// + /// Similar as UniTask.Yield but guaranteed run on next frame. + /// + public static UniTask NextFrame(PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately = false) + { + return new UniTask(NextFramePromise.Create(timing, cancellationToken, cancelImmediately, out var token), token); + } + +#if UNITY_2023_1_OR_NEWER + public static async UniTask WaitForEndOfFrame(CancellationToken cancellationToken = default) + { + await Awaitable.EndOfFrameAsync(cancellationToken); + } +#else + [Obsolete("Use WaitForEndOfFrame(MonoBehaviour) instead or UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate). Equivalent for coroutine's WaitForEndOfFrame requires MonoBehaviour(runner of Coroutine).")] + public static YieldAwaitable WaitForEndOfFrame() + { + return UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate); + } + + [Obsolete("Use WaitForEndOfFrame(MonoBehaviour) instead or UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate). Equivalent for coroutine's WaitForEndOfFrame requires MonoBehaviour(runner of Coroutine).")] + public static UniTask WaitForEndOfFrame(CancellationToken cancellationToken, bool cancelImmediately = false) + { + return UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate, cancellationToken, cancelImmediately); + } +#endif + + public static UniTask WaitForEndOfFrame(MonoBehaviour coroutineRunner) + { + var source = WaitForEndOfFramePromise.Create(coroutineRunner, CancellationToken.None, false, out var token); + return new UniTask(source, token); + } + + public static UniTask WaitForEndOfFrame(MonoBehaviour coroutineRunner, CancellationToken cancellationToken, bool cancelImmediately = false) + { + var source = WaitForEndOfFramePromise.Create(coroutineRunner, cancellationToken, cancelImmediately, out var token); + return new UniTask(source, token); + } + + /// + /// Same as UniTask.Yield(PlayerLoopTiming.LastFixedUpdate). + /// + public static YieldAwaitable WaitForFixedUpdate() + { + // use LastFixedUpdate instead of FixedUpdate + // https://github.com/Cysharp/UniTask/issues/377 + return UniTask.Yield(PlayerLoopTiming.LastFixedUpdate); + } + + /// + /// Same as UniTask.Yield(PlayerLoopTiming.LastFixedUpdate, cancellationToken). + /// + public static UniTask WaitForFixedUpdate(CancellationToken cancellationToken, bool cancelImmediately = false) + { + return UniTask.Yield(PlayerLoopTiming.LastFixedUpdate, cancellationToken, cancelImmediately); + } + + public static UniTask WaitForSeconds(float duration, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + return Delay(Mathf.RoundToInt(1000 * duration), ignoreTimeScale, delayTiming, cancellationToken, cancelImmediately); + } + + public static UniTask WaitForSeconds(int duration, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + return Delay(1000 * duration, ignoreTimeScale, delayTiming, cancellationToken, cancelImmediately); + } + + public static UniTask DelayFrame(int delayFrameCount, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + if (delayFrameCount < 0) + { + throw new ArgumentOutOfRangeException("Delay does not allow minus delayFrameCount. delayFrameCount:" + delayFrameCount); + } + + return new UniTask(DelayFramePromise.Create(delayFrameCount, delayTiming, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask Delay(int millisecondsDelay, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + var delayTimeSpan = TimeSpan.FromMilliseconds(millisecondsDelay); + return Delay(delayTimeSpan, ignoreTimeScale, delayTiming, cancellationToken, cancelImmediately); + } + + public static UniTask Delay(TimeSpan delayTimeSpan, bool ignoreTimeScale = false, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + var delayType = ignoreTimeScale ? DelayType.UnscaledDeltaTime : DelayType.DeltaTime; + return Delay(delayTimeSpan, delayType, delayTiming, cancellationToken, cancelImmediately); + } + + public static UniTask Delay(int millisecondsDelay, DelayType delayType, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + var delayTimeSpan = TimeSpan.FromMilliseconds(millisecondsDelay); + return Delay(delayTimeSpan, delayType, delayTiming, cancellationToken, cancelImmediately); + } + + public static UniTask Delay(TimeSpan delayTimeSpan, DelayType delayType, PlayerLoopTiming delayTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + if (delayTimeSpan < TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException("Delay does not allow minus delayTimeSpan. delayTimeSpan:" + delayTimeSpan); + } + +#if UNITY_EDITOR + // force use Realtime. + if (PlayerLoopHelper.IsMainThread && !UnityEditor.EditorApplication.isPlaying) + { + delayType = DelayType.Realtime; + } +#endif + + switch (delayType) + { + case DelayType.UnscaledDeltaTime: + { + return new UniTask(DelayIgnoreTimeScalePromise.Create(delayTimeSpan, delayTiming, cancellationToken, cancelImmediately, out var token), token); + } + case DelayType.Realtime: + { + return new UniTask(DelayRealtimePromise.Create(delayTimeSpan, delayTiming, cancellationToken, cancelImmediately, out var token), token); + } + case DelayType.DeltaTime: + default: + { + return new UniTask(DelayPromise.Create(delayTimeSpan, delayTiming, cancellationToken, cancelImmediately, out var token), token); + } + } + } + + sealed class YieldPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + YieldPromise nextNode; + public ref YieldPromise NextNode => ref nextNode; + + static YieldPromise() + { + TaskPool.RegisterSizeGetter(typeof(YieldPromise), () => pool.Size); + } + + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + UniTaskCompletionSourceCore core; + + YieldPromise() + { + } + + public static IUniTaskSource Create(PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new YieldPromise(); + } + + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (YieldPromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + core.TrySetResult(null); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class NextFramePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + NextFramePromise nextNode; + public ref NextFramePromise NextNode => ref nextNode; + + static NextFramePromise() + { + TaskPool.RegisterSizeGetter(typeof(NextFramePromise), () => pool.Size); + } + + int frameCount; + UniTaskCompletionSourceCore core; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + NextFramePromise() + { + } + + public static IUniTaskSource Create(PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new NextFramePromise(); + } + + result.frameCount = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (NextFramePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (frameCount == Time.frameCount) + { + return true; + } + + core.TrySetResult(AsyncUnit.Default); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + return pool.TryPush(this); + } + } + + sealed class WaitForEndOfFramePromise : IUniTaskSource, ITaskPoolNode, System.Collections.IEnumerator + { + static TaskPool pool; + WaitForEndOfFramePromise nextNode; + public ref WaitForEndOfFramePromise NextNode => ref nextNode; + + static WaitForEndOfFramePromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitForEndOfFramePromise), () => pool.Size); + } + + UniTaskCompletionSourceCore core; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + WaitForEndOfFramePromise() + { + } + + public static IUniTaskSource Create(MonoBehaviour coroutineRunner, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitForEndOfFramePromise(); + } + + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitForEndOfFramePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + coroutineRunner.StartCoroutine(result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + Reset(); // Reset Enumerator + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + return pool.TryPush(this); + } + + // Coroutine Runner implementation + + static readonly WaitForEndOfFrame waitForEndOfFrameYieldInstruction = new WaitForEndOfFrame(); + bool isFirst = true; + + object IEnumerator.Current => waitForEndOfFrameYieldInstruction; + + bool IEnumerator.MoveNext() + { + if (isFirst) + { + isFirst = false; + return true; // start WaitForEndOfFrame + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + core.TrySetResult(null); + return false; + } + + public void Reset() + { + isFirst = true; + } + } + + sealed class DelayFramePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + DelayFramePromise nextNode; + public ref DelayFramePromise NextNode => ref nextNode; + + static DelayFramePromise() + { + TaskPool.RegisterSizeGetter(typeof(DelayFramePromise), () => pool.Size); + } + + int initialFrame; + int delayFrameCount; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + int currentFrameCount; + UniTaskCompletionSourceCore core; + + DelayFramePromise() + { + } + + public static IUniTaskSource Create(int delayFrameCount, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new DelayFramePromise(); + } + + result.delayFrameCount = delayFrameCount; + result.cancellationToken = cancellationToken; + result.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (DelayFramePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (currentFrameCount == 0) + { + if (delayFrameCount == 0) // same as Yield + { + core.TrySetResult(AsyncUnit.Default); + return false; + } + + // skip in initial frame. + if (initialFrame == Time.frameCount) + { +#if UNITY_EDITOR + // force use Realtime. + if (PlayerLoopHelper.IsMainThread && !UnityEditor.EditorApplication.isPlaying) + { + //goto ++currentFrameCount + } + else + { + return true; + } +#else + return true; +#endif + } + } + + if (++currentFrameCount >= delayFrameCount) + { + core.TrySetResult(AsyncUnit.Default); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + currentFrameCount = default; + delayFrameCount = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class DelayPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + DelayPromise nextNode; + public ref DelayPromise NextNode => ref nextNode; + + static DelayPromise() + { + TaskPool.RegisterSizeGetter(typeof(DelayPromise), () => pool.Size); + } + + int initialFrame; + float delayTimeSpan; + float elapsed; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + DelayPromise() + { + } + + public static IUniTaskSource Create(TimeSpan delayTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new DelayPromise(); + } + + result.elapsed = 0.0f; + result.delayTimeSpan = (float)delayTimeSpan.TotalSeconds; + result.cancellationToken = cancellationToken; + result.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (DelayPromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (elapsed == 0.0f) + { + if (initialFrame == Time.frameCount) + { + return true; + } + } + + elapsed += Time.deltaTime; + if (elapsed >= delayTimeSpan) + { + core.TrySetResult(null); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + delayTimeSpan = default; + elapsed = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class DelayIgnoreTimeScalePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + DelayIgnoreTimeScalePromise nextNode; + public ref DelayIgnoreTimeScalePromise NextNode => ref nextNode; + + static DelayIgnoreTimeScalePromise() + { + TaskPool.RegisterSizeGetter(typeof(DelayIgnoreTimeScalePromise), () => pool.Size); + } + + float delayFrameTimeSpan; + float elapsed; + int initialFrame; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + DelayIgnoreTimeScalePromise() + { + } + + public static IUniTaskSource Create(TimeSpan delayFrameTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new DelayIgnoreTimeScalePromise(); + } + + result.elapsed = 0.0f; + result.delayFrameTimeSpan = (float)delayFrameTimeSpan.TotalSeconds; + result.initialFrame = PlayerLoopHelper.IsMainThread ? Time.frameCount : -1; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (DelayIgnoreTimeScalePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (elapsed == 0.0f) + { + if (initialFrame == Time.frameCount) + { + return true; + } + } + + elapsed += Time.unscaledDeltaTime; + if (elapsed >= delayFrameTimeSpan) + { + core.TrySetResult(null); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + delayFrameTimeSpan = default; + elapsed = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class DelayRealtimePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + DelayRealtimePromise nextNode; + public ref DelayRealtimePromise NextNode => ref nextNode; + + static DelayRealtimePromise() + { + TaskPool.RegisterSizeGetter(typeof(DelayRealtimePromise), () => pool.Size); + } + + long delayTimeSpanTicks; + ValueStopwatch stopwatch; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + DelayRealtimePromise() + { + } + + public static IUniTaskSource Create(TimeSpan delayTimeSpan, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new DelayRealtimePromise(); + } + + result.stopwatch = ValueStopwatch.StartNew(); + result.delayTimeSpanTicks = delayTimeSpan.Ticks; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (DelayRealtimePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (stopwatch.IsInvalid) + { + core.TrySetResult(AsyncUnit.Default); + return false; + } + + if (stopwatch.ElapsedTicks >= delayTimeSpanTicks) + { + core.TrySetResult(AsyncUnit.Default); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + stopwatch = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + } + + public readonly struct YieldAwaitable + { + readonly PlayerLoopTiming timing; + + public YieldAwaitable(PlayerLoopTiming timing) + { + this.timing = timing; + } + + public Awaiter GetAwaiter() + { + return new Awaiter(timing); + } + + public UniTask ToUniTask() + { + return UniTask.Yield(timing, CancellationToken.None); + } + + public readonly struct Awaiter : ICriticalNotifyCompletion + { + readonly PlayerLoopTiming timing; + + public Awaiter(PlayerLoopTiming timing) + { + this.timing = timing; + } + + public bool IsCompleted => false; + + public void GetResult() { } + + public void OnCompleted(Action continuation) + { + PlayerLoopHelper.AddContinuation(timing, continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + PlayerLoopHelper.AddContinuation(timing, continuation); + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Delay.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Delay.cs.meta new file mode 100644 index 00000000..08ce5793 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Delay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ecff7972251de0848b2c0fa89bbd3489 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Factory.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Factory.cs new file mode 100644 index 00000000..8bdec75f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Factory.cs @@ -0,0 +1,701 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + static readonly UniTask CanceledUniTask = new Func(() => + { + return new UniTask(new CanceledResultSource(CancellationToken.None), 0); + })(); + + static class CanceledUniTaskCache + { + public static readonly UniTask Task; + + static CanceledUniTaskCache() + { + Task = new UniTask(new CanceledResultSource(CancellationToken.None), 0); + } + } + + public static readonly UniTask CompletedTask = new UniTask(); + + public static UniTask FromException(Exception ex) + { + if (ex is OperationCanceledException oce) + { + return FromCanceled(oce.CancellationToken); + } + + return new UniTask(new ExceptionResultSource(ex), 0); + } + + public static UniTask FromException(Exception ex) + { + if (ex is OperationCanceledException oce) + { + return FromCanceled(oce.CancellationToken); + } + + return new UniTask(new ExceptionResultSource(ex), 0); + } + + public static UniTask FromResult(T value) + { + return new UniTask(value); + } + + public static UniTask FromCanceled(CancellationToken cancellationToken = default) + { + if (cancellationToken == CancellationToken.None) + { + return CanceledUniTask; + } + else + { + return new UniTask(new CanceledResultSource(cancellationToken), 0); + } + } + + public static UniTask FromCanceled(CancellationToken cancellationToken = default) + { + if (cancellationToken == CancellationToken.None) + { + return CanceledUniTaskCache.Task; + } + else + { + return new UniTask(new CanceledResultSource(cancellationToken), 0); + } + } + + public static UniTask Create(Func factory) + { + return factory(); + } + + public static UniTask Create(Func factory, CancellationToken cancellationToken) + { + return factory(cancellationToken); + } + + public static UniTask Create(T state, Func factory) + { + return factory(state); + } + + public static UniTask Create(Func> factory) + { + return factory(); + } + + public static AsyncLazy Lazy(Func factory) + { + return new AsyncLazy(factory); + } + + public static AsyncLazy Lazy(Func> factory) + { + return new AsyncLazy(factory); + } + + /// + /// helper of fire and forget void action. + /// + public static void Void(Func asyncAction) + { + asyncAction().Forget(); + } + + /// + /// helper of fire and forget void action. + /// + public static void Void(Func asyncAction, CancellationToken cancellationToken) + { + asyncAction(cancellationToken).Forget(); + } + + /// + /// helper of fire and forget void action. + /// + public static void Void(Func asyncAction, T state) + { + asyncAction(state).Forget(); + } + + /// + /// helper of create add UniTaskVoid to delegate. + /// For example: FooAction = UniTask.Action(async () => { /* */ }) + /// + public static Action Action(Func asyncAction) + { + return () => asyncAction().Forget(); + } + + /// + /// helper of create add UniTaskVoid to delegate. + /// + public static Action Action(Func asyncAction, CancellationToken cancellationToken) + { + return () => asyncAction(cancellationToken).Forget(); + } + + /// + /// helper of create add UniTaskVoid to delegate. + /// + public static Action Action(T state, Func asyncAction) + { + return () => asyncAction(state).Forget(); + } + +#if UNITY_2018_3_OR_NEWER + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async () => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction) + { + return () => asyncAction().Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(FooAsync, this.GetCancellationTokenOnDestroy())) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction, CancellationToken cancellationToken) + { + return () => asyncAction(cancellationToken).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(FooAsync, Argument)) + /// + public static UnityEngine.Events.UnityAction UnityAction(T state, Func asyncAction) + { + return () => asyncAction(state).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T arg) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction) + { + return (arg) => asyncAction(arg).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T0 arg0, T1 arg1) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction) + { + return (arg0, arg1) => asyncAction(arg0, arg1).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T0 arg0, T1 arg1, T2 arg2) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction) + { + return (arg0, arg1, arg2) => asyncAction(arg0, arg1, arg2).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T0 arg0, T1 arg1, T2 arg2, T3 arg3) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction) + { + return (arg0, arg1, arg2, arg3) => asyncAction(arg0, arg1, arg2, arg3).Forget(); + } + + // + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T arg, CancellationToken cancellationToken) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction, CancellationToken cancellationToken) + { + return (arg) => asyncAction(arg, cancellationToken).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T0 arg0, T1 arg1, CancellationToken cancellationToken) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction, CancellationToken cancellationToken) + { + return (arg0, arg1) => asyncAction(arg0, arg1, cancellationToken).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T0 arg0, T1 arg1, T2 arg2, CancellationToken cancellationToken) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction, CancellationToken cancellationToken) + { + return (arg0, arg1, arg2) => asyncAction(arg0, arg1, arg2, cancellationToken).Forget(); + } + + /// + /// Create async void(UniTaskVoid) UnityAction. + /// For example: onClick.AddListener(UniTask.UnityAction(async (T0 arg0, T1 arg1, T2 arg2, T3 arg3, CancellationToken cancellationToken) => { /* */ } )) + /// + public static UnityEngine.Events.UnityAction UnityAction(Func asyncAction, CancellationToken cancellationToken) + { + return (arg0, arg1, arg2, arg3) => asyncAction(arg0, arg1, arg2, arg3, cancellationToken).Forget(); + } + +#endif + + /// + /// Defer the task creation just before call await. + /// + public static UniTask Defer(Func factory) + { + return new UniTask(new DeferPromise(factory), 0); + } + + /// + /// Defer the task creation just before call await. + /// + public static UniTask Defer(Func> factory) + { + return new UniTask(new DeferPromise(factory), 0); + } + + /// + /// Defer the task creation just before call await. + /// + public static UniTask Defer(TState state, Func factory) + { + return new UniTask(new DeferPromiseWithState(state, factory), 0); + } + + /// + /// Defer the task creation just before call await. + /// + public static UniTask Defer(TState state, Func> factory) + { + return new UniTask(new DeferPromiseWithState(state, factory), 0); + } + + /// + /// Never complete. + /// + public static UniTask Never(CancellationToken cancellationToken) + { + return new UniTask(new NeverPromise(cancellationToken), 0); + } + + /// + /// Never complete. + /// + public static UniTask Never(CancellationToken cancellationToken) + { + return new UniTask(new NeverPromise(cancellationToken), 0); + } + + sealed class ExceptionResultSource : IUniTaskSource + { + readonly ExceptionDispatchInfo exception; + bool calledGet; + + public ExceptionResultSource(Exception exception) + { + this.exception = ExceptionDispatchInfo.Capture(exception); + } + + public void GetResult(short token) + { + if (!calledGet) + { + calledGet = true; + GC.SuppressFinalize(this); + } + exception.Throw(); + } + + public UniTaskStatus GetStatus(short token) + { + return UniTaskStatus.Faulted; + } + + public UniTaskStatus UnsafeGetStatus() + { + return UniTaskStatus.Faulted; + } + + public void OnCompleted(Action continuation, object state, short token) + { + continuation(state); + } + + ~ExceptionResultSource() + { + if (!calledGet) + { + UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException); + } + } + } + + sealed class ExceptionResultSource : IUniTaskSource + { + readonly ExceptionDispatchInfo exception; + bool calledGet; + + public ExceptionResultSource(Exception exception) + { + this.exception = ExceptionDispatchInfo.Capture(exception); + } + + public T GetResult(short token) + { + if (!calledGet) + { + calledGet = true; + GC.SuppressFinalize(this); + } + exception.Throw(); + return default; + } + + void IUniTaskSource.GetResult(short token) + { + if (!calledGet) + { + calledGet = true; + GC.SuppressFinalize(this); + } + exception.Throw(); + } + + public UniTaskStatus GetStatus(short token) + { + return UniTaskStatus.Faulted; + } + + public UniTaskStatus UnsafeGetStatus() + { + return UniTaskStatus.Faulted; + } + + public void OnCompleted(Action continuation, object state, short token) + { + continuation(state); + } + + ~ExceptionResultSource() + { + if (!calledGet) + { + UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException); + } + } + } + + sealed class CanceledResultSource : IUniTaskSource + { + readonly CancellationToken cancellationToken; + + public CanceledResultSource(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public void GetResult(short token) + { + throw new OperationCanceledException(cancellationToken); + } + + public UniTaskStatus GetStatus(short token) + { + return UniTaskStatus.Canceled; + } + + public UniTaskStatus UnsafeGetStatus() + { + return UniTaskStatus.Canceled; + } + + public void OnCompleted(Action continuation, object state, short token) + { + continuation(state); + } + } + + sealed class CanceledResultSource : IUniTaskSource + { + readonly CancellationToken cancellationToken; + + public CanceledResultSource(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public T GetResult(short token) + { + throw new OperationCanceledException(cancellationToken); + } + + void IUniTaskSource.GetResult(short token) + { + throw new OperationCanceledException(cancellationToken); + } + + public UniTaskStatus GetStatus(short token) + { + return UniTaskStatus.Canceled; + } + + public UniTaskStatus UnsafeGetStatus() + { + return UniTaskStatus.Canceled; + } + + public void OnCompleted(Action continuation, object state, short token) + { + continuation(state); + } + } + + sealed class DeferPromise : IUniTaskSource + { + Func factory; + UniTask task; + UniTask.Awaiter awaiter; + + public DeferPromise(Func factory) + { + this.factory = factory; + } + + public void GetResult(short token) + { + awaiter.GetResult(); + } + + public UniTaskStatus GetStatus(short token) + { + var f = Interlocked.Exchange(ref factory, null); + if (f != null) + { + task = f(); + awaiter = task.GetAwaiter(); + } + + return task.Status; + } + + public void OnCompleted(Action continuation, object state, short token) + { + awaiter.SourceOnCompleted(continuation, state); + } + + public UniTaskStatus UnsafeGetStatus() + { + return task.Status; + } + } + + sealed class DeferPromise : IUniTaskSource + { + Func> factory; + UniTask task; + UniTask.Awaiter awaiter; + + public DeferPromise(Func> factory) + { + this.factory = factory; + } + + public T GetResult(short token) + { + return awaiter.GetResult(); + } + + void IUniTaskSource.GetResult(short token) + { + awaiter.GetResult(); + } + + public UniTaskStatus GetStatus(short token) + { + var f = Interlocked.Exchange(ref factory, null); + if (f != null) + { + task = f(); + awaiter = task.GetAwaiter(); + } + + return task.Status; + } + + public void OnCompleted(Action continuation, object state, short token) + { + awaiter.SourceOnCompleted(continuation, state); + } + + public UniTaskStatus UnsafeGetStatus() + { + return task.Status; + } + } + + sealed class DeferPromiseWithState : IUniTaskSource + { + Func factory; + TState argument; + UniTask task; + UniTask.Awaiter awaiter; + + public DeferPromiseWithState(TState argument, Func factory) + { + this.argument = argument; + this.factory = factory; + } + + public void GetResult(short token) + { + awaiter.GetResult(); + } + + public UniTaskStatus GetStatus(short token) + { + var f = Interlocked.Exchange(ref factory, null); + if (f != null) + { + task = f(argument); + awaiter = task.GetAwaiter(); + } + + return task.Status; + } + + public void OnCompleted(Action continuation, object state, short token) + { + awaiter.SourceOnCompleted(continuation, state); + } + + public UniTaskStatus UnsafeGetStatus() + { + return task.Status; + } + } + + sealed class DeferPromiseWithState : IUniTaskSource + { + Func> factory; + TState argument; + UniTask task; + UniTask.Awaiter awaiter; + + public DeferPromiseWithState(TState argument, Func> factory) + { + this.argument = argument; + this.factory = factory; + } + + public TResult GetResult(short token) + { + return awaiter.GetResult(); + } + + void IUniTaskSource.GetResult(short token) + { + awaiter.GetResult(); + } + + public UniTaskStatus GetStatus(short token) + { + var f = Interlocked.Exchange(ref factory, null); + if (f != null) + { + task = f(argument); + awaiter = task.GetAwaiter(); + } + + return task.Status; + } + + public void OnCompleted(Action continuation, object state, short token) + { + awaiter.SourceOnCompleted(continuation, state); + } + + public UniTaskStatus UnsafeGetStatus() + { + return task.Status; + } + } + + sealed class NeverPromise : IUniTaskSource + { + static readonly Action cancellationCallback = CancellationCallback; + + CancellationToken cancellationToken; + UniTaskCompletionSourceCore core; + + public NeverPromise(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + if (this.cancellationToken.CanBeCanceled) + { + this.cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + } + + static void CancellationCallback(object state) + { + var self = (NeverPromise)state; + self.core.TrySetCanceled(self.cancellationToken); + } + + public T GetResult(short token) + { + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + void IUniTaskSource.GetResult(short token) + { + core.GetResult(token); + } + } + } + + internal static class CompletedTasks + { + public static readonly UniTask AsyncUnit = UniTask.FromResult(Cysharp.Threading.Tasks.AsyncUnit.Default); + public static readonly UniTask True = UniTask.FromResult(true); + public static readonly UniTask False = UniTask.FromResult(false); + public static readonly UniTask Zero = UniTask.FromResult(0); + public static readonly UniTask MinusOne = UniTask.FromResult(-1); + public static readonly UniTask One = UniTask.FromResult(1); + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Factory.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Factory.cs.meta new file mode 100644 index 00000000..31bc0c95 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Factory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e12b66d6b9bd7845b04a594cbe386b4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Run.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Run.cs new file mode 100644 index 00000000..ac3e7958 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Run.cs @@ -0,0 +1,289 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + #region OBSOLETE_RUN + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Action action, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(action, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Action action, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(action, state, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Func action, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(action, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Func action, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(action, state, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Func func, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(func, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Func> func, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(func, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Func func, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(func, state, configureAwait, cancellationToken); + } + + [Obsolete("UniTask.Run is similar as Task.Run, it uses ThreadPool. For equivalent behaviour, use UniTask.RunOnThreadPool instead. If you don't want to use ThreadPool, you can use UniTask.Void(async void) or UniTask.Create(async UniTask) too.")] + public static UniTask Run(Func> func, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + return RunOnThreadPool(func, state, configureAwait, cancellationToken); + } + + #endregion + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Action action, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + action(); + } + finally + { + await UniTask.Yield(); + } + } + else + { + action(); + } + + cancellationToken.ThrowIfCancellationRequested(); + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Action action, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + action(state); + } + finally + { + await UniTask.Yield(); + } + } + else + { + action(state); + } + + cancellationToken.ThrowIfCancellationRequested(); + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Func action, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + await action(); + } + finally + { + await UniTask.Yield(); + } + } + else + { + await action(); + } + + cancellationToken.ThrowIfCancellationRequested(); + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Func action, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + await action(state); + } + finally + { + await UniTask.Yield(); + } + } + else + { + await action(state); + } + + cancellationToken.ThrowIfCancellationRequested(); + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Func func, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + return func(); + } + finally + { + await UniTask.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + } + } + else + { + return func(); + } + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Func> func, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + return await func(); + } + finally + { + cancellationToken.ThrowIfCancellationRequested(); + await UniTask.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + } + } + else + { + var result = await func(); + cancellationToken.ThrowIfCancellationRequested(); + return result; + } + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Func func, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + return func(state); + } + finally + { + await UniTask.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + } + } + else + { + return func(state); + } + } + + /// Run action on the threadPool and return to main thread if configureAwait = true. + public static async UniTask RunOnThreadPool(Func> func, object state, bool configureAwait = true, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + await UniTask.SwitchToThreadPool(); + + cancellationToken.ThrowIfCancellationRequested(); + + if (configureAwait) + { + try + { + return await func(state); + } + finally + { + cancellationToken.ThrowIfCancellationRequested(); + await UniTask.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + } + } + else + { + var result = await func(state); + cancellationToken.ThrowIfCancellationRequested(); + return result; + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Run.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Run.cs.meta new file mode 100644 index 00000000..9a780aea --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Run.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8473162fc285a5f44bcca90f7da073e7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Threading.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Threading.cs new file mode 100644 index 00000000..71d6aec2 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Threading.cs @@ -0,0 +1,412 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { +#if UNITY_2018_3_OR_NEWER + + /// + /// If running on mainthread, do nothing. Otherwise, same as UniTask.Yield(PlayerLoopTiming.Update). + /// + public static SwitchToMainThreadAwaitable SwitchToMainThread(CancellationToken cancellationToken = default) + { + return new SwitchToMainThreadAwaitable(PlayerLoopTiming.Update, cancellationToken); + } + + /// + /// If running on mainthread, do nothing. Otherwise, same as UniTask.Yield(timing). + /// + public static SwitchToMainThreadAwaitable SwitchToMainThread(PlayerLoopTiming timing, CancellationToken cancellationToken = default) + { + return new SwitchToMainThreadAwaitable(timing, cancellationToken); + } + + /// + /// Return to mainthread(same as await SwitchToMainThread) after using scope is closed. + /// + public static ReturnToMainThread ReturnToMainThread(CancellationToken cancellationToken = default) + { + return new ReturnToMainThread(PlayerLoopTiming.Update, cancellationToken); + } + + /// + /// Return to mainthread(same as await SwitchToMainThread) after using scope is closed. + /// + public static ReturnToMainThread ReturnToMainThread(PlayerLoopTiming timing, CancellationToken cancellationToken = default) + { + return new ReturnToMainThread(timing, cancellationToken); + } + + /// + /// Queue the action to PlayerLoop. + /// + public static void Post(Action action, PlayerLoopTiming timing = PlayerLoopTiming.Update) + { + PlayerLoopHelper.AddContinuation(timing, action); + } + +#endif + + public static SwitchToThreadPoolAwaitable SwitchToThreadPool() + { + return new SwitchToThreadPoolAwaitable(); + } + + /// + /// Note: use SwitchToThreadPool is recommended. + /// + public static SwitchToTaskPoolAwaitable SwitchToTaskPool() + { + return new SwitchToTaskPoolAwaitable(); + } + + public static SwitchToSynchronizationContextAwaitable SwitchToSynchronizationContext(SynchronizationContext synchronizationContext, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(synchronizationContext, nameof(synchronizationContext)); + return new SwitchToSynchronizationContextAwaitable(synchronizationContext, cancellationToken); + } + + public static ReturnToSynchronizationContext ReturnToSynchronizationContext(SynchronizationContext synchronizationContext, CancellationToken cancellationToken = default) + { + return new ReturnToSynchronizationContext(synchronizationContext, false, cancellationToken); + } + + public static ReturnToSynchronizationContext ReturnToCurrentSynchronizationContext(bool dontPostWhenSameContext = true, CancellationToken cancellationToken = default) + { + return new ReturnToSynchronizationContext(SynchronizationContext.Current, dontPostWhenSameContext, cancellationToken); + } + } + +#if UNITY_2018_3_OR_NEWER + + public struct SwitchToMainThreadAwaitable + { + readonly PlayerLoopTiming playerLoopTiming; + readonly CancellationToken cancellationToken; + + public SwitchToMainThreadAwaitable(PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken) + { + this.playerLoopTiming = playerLoopTiming; + this.cancellationToken = cancellationToken; + } + + public Awaiter GetAwaiter() => new Awaiter(playerLoopTiming, cancellationToken); + + public struct Awaiter : ICriticalNotifyCompletion + { + readonly PlayerLoopTiming playerLoopTiming; + readonly CancellationToken cancellationToken; + + public Awaiter(PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken) + { + this.playerLoopTiming = playerLoopTiming; + this.cancellationToken = cancellationToken; + } + + public bool IsCompleted + { + get + { + var currentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId; + if (PlayerLoopHelper.MainThreadId == currentThreadId) + { + return true; // run immediate. + } + else + { + return false; // register continuation. + } + } + } + + public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); } + + public void OnCompleted(Action continuation) + { + PlayerLoopHelper.AddContinuation(playerLoopTiming, continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + PlayerLoopHelper.AddContinuation(playerLoopTiming, continuation); + } + } + } + + public struct ReturnToMainThread + { + readonly PlayerLoopTiming playerLoopTiming; + readonly CancellationToken cancellationToken; + + public ReturnToMainThread(PlayerLoopTiming playerLoopTiming, CancellationToken cancellationToken) + { + this.playerLoopTiming = playerLoopTiming; + this.cancellationToken = cancellationToken; + } + + public Awaiter DisposeAsync() + { + return new Awaiter(playerLoopTiming, cancellationToken); // run immediate. + } + + public readonly struct Awaiter : ICriticalNotifyCompletion + { + readonly PlayerLoopTiming timing; + readonly CancellationToken cancellationToken; + + public Awaiter(PlayerLoopTiming timing, CancellationToken cancellationToken) + { + this.timing = timing; + this.cancellationToken = cancellationToken; + } + + public Awaiter GetAwaiter() => this; + + public bool IsCompleted => PlayerLoopHelper.MainThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId; + + public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); } + + public void OnCompleted(Action continuation) + { + PlayerLoopHelper.AddContinuation(timing, continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + PlayerLoopHelper.AddContinuation(timing, continuation); + } + } + } + +#endif + + public struct SwitchToThreadPoolAwaitable + { + public Awaiter GetAwaiter() => new Awaiter(); + + public struct Awaiter : ICriticalNotifyCompletion + { + static readonly WaitCallback switchToCallback = Callback; + + public bool IsCompleted => false; + public void GetResult() { } + + public void OnCompleted(Action continuation) + { + ThreadPool.QueueUserWorkItem(switchToCallback, continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { +#if NETCOREAPP3_1 + ThreadPool.UnsafeQueueUserWorkItem(ThreadPoolWorkItem.Create(continuation), false); +#else + ThreadPool.UnsafeQueueUserWorkItem(switchToCallback, continuation); +#endif + } + + static void Callback(object state) + { + var continuation = (Action)state; + continuation(); + } + } + +#if NETCOREAPP3_1 + + sealed class ThreadPoolWorkItem : IThreadPoolWorkItem, ITaskPoolNode + { + static TaskPool pool; + ThreadPoolWorkItem nextNode; + public ref ThreadPoolWorkItem NextNode => ref nextNode; + + static ThreadPoolWorkItem() + { + TaskPool.RegisterSizeGetter(typeof(ThreadPoolWorkItem), () => pool.Size); + } + + Action continuation; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ThreadPoolWorkItem Create(Action continuation) + { + if (!pool.TryPop(out var item)) + { + item = new ThreadPoolWorkItem(); + } + + item.continuation = continuation; + return item; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Execute() + { + var call = continuation; + continuation = null; + if (call != null) + { + pool.TryPush(this); + call.Invoke(); + } + } + } + +#endif + } + + public struct SwitchToTaskPoolAwaitable + { + public Awaiter GetAwaiter() => new Awaiter(); + + public struct Awaiter : ICriticalNotifyCompletion + { + static readonly Action switchToCallback = Callback; + + public bool IsCompleted => false; + public void GetResult() { } + + public void OnCompleted(Action continuation) + { + Task.Factory.StartNew(switchToCallback, continuation, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + public void UnsafeOnCompleted(Action continuation) + { + Task.Factory.StartNew(switchToCallback, continuation, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + } + + static void Callback(object state) + { + var continuation = (Action)state; + continuation(); + } + } + } + + public struct SwitchToSynchronizationContextAwaitable + { + readonly SynchronizationContext synchronizationContext; + readonly CancellationToken cancellationToken; + + public SwitchToSynchronizationContextAwaitable(SynchronizationContext synchronizationContext, CancellationToken cancellationToken) + { + this.synchronizationContext = synchronizationContext; + this.cancellationToken = cancellationToken; + } + + public Awaiter GetAwaiter() => new Awaiter(synchronizationContext, cancellationToken); + + public struct Awaiter : ICriticalNotifyCompletion + { + static readonly SendOrPostCallback switchToCallback = Callback; + readonly SynchronizationContext synchronizationContext; + readonly CancellationToken cancellationToken; + + public Awaiter(SynchronizationContext synchronizationContext, CancellationToken cancellationToken) + { + this.synchronizationContext = synchronizationContext; + this.cancellationToken = cancellationToken; + } + + public bool IsCompleted => false; + public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); } + + public void OnCompleted(Action continuation) + { + synchronizationContext.Post(switchToCallback, continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + synchronizationContext.Post(switchToCallback, continuation); + } + + static void Callback(object state) + { + var continuation = (Action)state; + continuation(); + } + } + } + + public struct ReturnToSynchronizationContext + { + readonly SynchronizationContext syncContext; + readonly bool dontPostWhenSameContext; + readonly CancellationToken cancellationToken; + + public ReturnToSynchronizationContext(SynchronizationContext syncContext, bool dontPostWhenSameContext, CancellationToken cancellationToken) + { + this.syncContext = syncContext; + this.dontPostWhenSameContext = dontPostWhenSameContext; + this.cancellationToken = cancellationToken; + } + + public Awaiter DisposeAsync() + { + return new Awaiter(syncContext, dontPostWhenSameContext, cancellationToken); + } + + public struct Awaiter : ICriticalNotifyCompletion + { + static readonly SendOrPostCallback switchToCallback = Callback; + + readonly SynchronizationContext synchronizationContext; + readonly bool dontPostWhenSameContext; + readonly CancellationToken cancellationToken; + + public Awaiter(SynchronizationContext synchronizationContext, bool dontPostWhenSameContext, CancellationToken cancellationToken) + { + this.synchronizationContext = synchronizationContext; + this.dontPostWhenSameContext = dontPostWhenSameContext; + this.cancellationToken = cancellationToken; + } + + public Awaiter GetAwaiter() => this; + + public bool IsCompleted + { + get + { + if (!dontPostWhenSameContext) return false; + + var current = SynchronizationContext.Current; + if (current == synchronizationContext) + { + return true; + } + else + { + return false; + } + } + } + + public void GetResult() { cancellationToken.ThrowIfCancellationRequested(); } + + public void OnCompleted(Action continuation) + { + synchronizationContext.Post(switchToCallback, continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + synchronizationContext.Post(switchToCallback, continuation); + } + + static void Callback(object state) + { + var continuation = (Action)state; + continuation(); + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Threading.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Threading.cs.meta new file mode 100644 index 00000000..fa512b8c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.Threading.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4132ea600454134439fa2c7eb931b5e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WaitUntil.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WaitUntil.cs new file mode 100644 index 00000000..b1133535 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WaitUntil.cs @@ -0,0 +1,956 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Diagnostics.Tracing; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + public static UniTask WaitUntil(Func predicate, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + return new UniTask(WaitUntilPromise.Create(predicate, timing, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask WaitUntil(T state, Func predicate, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + return new UniTask(WaitUntilPromise.Create(state, predicate, timing, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask WaitWhile(Func predicate, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + return new UniTask(WaitWhilePromise.Create(predicate, timing, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask WaitWhile(T state, Func predicate, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + return new UniTask(WaitWhilePromise.Create(state, predicate, timing, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask WaitUntilCanceled(CancellationToken cancellationToken, PlayerLoopTiming timing = PlayerLoopTiming.Update, bool completeImmediately = false) + { + return new UniTask(WaitUntilCanceledPromise.Create(cancellationToken, timing, completeImmediately, out var token), token); + } + + public static UniTask WaitUntilValueChanged(T target, Func monitorFunction, PlayerLoopTiming monitorTiming = PlayerLoopTiming.Update, IEqualityComparer equalityComparer = null, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + where T : class + { + var unityObject = target as UnityEngine.Object; + var isUnityObject = target is UnityEngine.Object; // don't use (unityObject == null) + + return new UniTask(isUnityObject + ? WaitUntilValueChangedUnityObjectPromise.Create(target, monitorFunction, equalityComparer, monitorTiming, cancellationToken, cancelImmediately, out var token) + : WaitUntilValueChangedStandardObjectPromise.Create(target, monitorFunction, equalityComparer, monitorTiming, cancellationToken, cancelImmediately, out token), token); + } + + sealed class WaitUntilPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + WaitUntilPromise nextNode; + public ref WaitUntilPromise NextNode => ref nextNode; + + static WaitUntilPromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitUntilPromise), () => pool.Size); + } + + Func predicate; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitUntilPromise() + { + } + + public static IUniTaskSource Create(Func predicate, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitUntilPromise(); + } + + result.predicate = predicate; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitUntilPromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + try + { + if (!predicate()) + { + return true; + } + } + catch (Exception ex) + { + core.TrySetException(ex); + return false; + } + + core.TrySetResult(null); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + predicate = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class WaitUntilPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> + { + static TaskPool> pool; + WaitUntilPromise nextNode; + public ref WaitUntilPromise NextNode => ref nextNode; + + static WaitUntilPromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitUntilPromise), () => pool.Size); + } + + Func predicate; + T argument; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitUntilPromise() + { + } + + public static IUniTaskSource Create(T argument, Func predicate, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitUntilPromise(); + } + + result.predicate = predicate; + result.argument = argument; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitUntilPromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + try + { + if (!predicate(argument)) + { + return true; + } + } + catch (Exception ex) + { + core.TrySetException(ex); + return false; + } + + core.TrySetResult(null); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + predicate = default; + argument = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class WaitWhilePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + WaitWhilePromise nextNode; + public ref WaitWhilePromise NextNode => ref nextNode; + + static WaitWhilePromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitWhilePromise), () => pool.Size); + } + + Func predicate; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitWhilePromise() + { + } + + public static IUniTaskSource Create(Func predicate, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitWhilePromise(); + } + + result.predicate = predicate; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitWhilePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + try + { + if (predicate()) + { + return true; + } + } + catch (Exception ex) + { + core.TrySetException(ex); + return false; + } + + core.TrySetResult(null); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + predicate = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class WaitWhilePromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> + { + static TaskPool> pool; + WaitWhilePromise nextNode; + public ref WaitWhilePromise NextNode => ref nextNode; + + static WaitWhilePromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitWhilePromise), () => pool.Size); + } + + Func predicate; + T argument; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitWhilePromise() + { + } + + public static IUniTaskSource Create(T argument, Func predicate, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitWhilePromise(); + } + + result.predicate = predicate; + result.argument = argument; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitWhilePromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + try + { + if (predicate(argument)) + { + return true; + } + } + catch (Exception ex) + { + core.TrySetException(ex); + return false; + } + + core.TrySetResult(null); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + predicate = default; + argument = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class WaitUntilCanceledPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + WaitUntilCanceledPromise nextNode; + public ref WaitUntilCanceledPromise NextNode => ref nextNode; + + static WaitUntilCanceledPromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitUntilCanceledPromise), () => pool.Size); + } + + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitUntilCanceledPromise() + { + } + + public static IUniTaskSource Create(CancellationToken cancellationToken, PlayerLoopTiming timing, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitUntilCanceledPromise(); + } + + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitUntilCanceledPromise)state; + promise.core.TrySetResult(null); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetResult(null); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + // where T : UnityEngine.Object, can not add constraint + sealed class WaitUntilValueChangedUnityObjectPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> + { + static TaskPool> pool; + WaitUntilValueChangedUnityObjectPromise nextNode; + public ref WaitUntilValueChangedUnityObjectPromise NextNode => ref nextNode; + + static WaitUntilValueChangedUnityObjectPromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitUntilValueChangedUnityObjectPromise), () => pool.Size); + } + + T target; + UnityEngine.Object targetAsUnityObject; + U currentValue; + Func monitorFunction; + IEqualityComparer equalityComparer; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitUntilValueChangedUnityObjectPromise() + { + } + + public static IUniTaskSource Create(T target, Func monitorFunction, IEqualityComparer equalityComparer, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitUntilValueChangedUnityObjectPromise(); + } + + result.target = target; + result.targetAsUnityObject = target as UnityEngine.Object; + result.monitorFunction = monitorFunction; + result.currentValue = monitorFunction(target); + result.equalityComparer = equalityComparer ?? UnityEqualityComparer.GetDefault(); + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitUntilValueChangedUnityObjectPromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public U GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested || targetAsUnityObject == null) // destroyed = cancel. + { + core.TrySetCanceled(cancellationToken); + return false; + } + + U nextValue = default(U); + try + { + nextValue = monitorFunction(target); + if (equalityComparer.Equals(currentValue, nextValue)) + { + return true; + } + } + catch (Exception ex) + { + core.TrySetException(ex); + return false; + } + + core.TrySetResult(nextValue); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + target = default; + currentValue = default; + monitorFunction = default; + equalityComparer = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + sealed class WaitUntilValueChangedStandardObjectPromise : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> + where T : class + { + static TaskPool> pool; + WaitUntilValueChangedStandardObjectPromise nextNode; + public ref WaitUntilValueChangedStandardObjectPromise NextNode => ref nextNode; + + static WaitUntilValueChangedStandardObjectPromise() + { + TaskPool.RegisterSizeGetter(typeof(WaitUntilValueChangedStandardObjectPromise), () => pool.Size); + } + + WeakReference target; + U currentValue; + Func monitorFunction; + IEqualityComparer equalityComparer; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + + UniTaskCompletionSourceCore core; + + WaitUntilValueChangedStandardObjectPromise() + { + } + + public static IUniTaskSource Create(T target, Func monitorFunction, IEqualityComparer equalityComparer, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new WaitUntilValueChangedStandardObjectPromise(); + } + + result.target = new WeakReference(target, false); // wrap in WeakReference. + result.monitorFunction = monitorFunction; + result.currentValue = monitorFunction(target); + result.equalityComparer = equalityComparer ?? UnityEqualityComparer.GetDefault(); + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (WaitUntilValueChangedStandardObjectPromise)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public U GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested || !target.TryGetTarget(out var t)) // doesn't find = cancel. + { + core.TrySetCanceled(cancellationToken); + return false; + } + + U nextValue = default(U); + try + { + nextValue = monitorFunction(t); + if (equalityComparer.Equals(currentValue, nextValue)) + { + return true; + } + } + catch (Exception ex) + { + core.TrySetException(ex); + return false; + } + + core.TrySetResult(nextValue); + return false; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + target = default; + currentValue = default; + monitorFunction = default; + equalityComparer = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WaitUntil.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WaitUntil.cs.meta new file mode 100644 index 00000000..6e64dc7e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WaitUntil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87c9c533491903a4288536b5ac173db8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.Generated.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.Generated.cs new file mode 100644 index 00000000..9ef07d62 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.Generated.cs @@ -0,0 +1,5011 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + + public static UniTask<(T1, T2)> WhenAll(UniTask task1, UniTask task2) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2)>(new WhenAllPromise(task1, task2), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2)> + { + T1 t1 = default; + T2 t2 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2)> core; + + public WhenAllPromise(UniTask task1, UniTask task2) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 2) + { + self.core.TrySetResult((self.t1, self.t2)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 2) + { + self.core.TrySetResult((self.t1, self.t2)); + } + } + + + public (T1, T2) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3)> WhenAll(UniTask task1, UniTask task2, UniTask task3) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3)>(new WhenAllPromise(task1, task2, task3), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 3) + { + self.core.TrySetResult((self.t1, self.t2, self.t3)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 3) + { + self.core.TrySetResult((self.t1, self.t2, self.t3)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 3) + { + self.core.TrySetResult((self.t1, self.t2, self.t3)); + } + } + + + public (T1, T2, T3) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4)>(new WhenAllPromise(task1, task2, task3, task4), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 4) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 4) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 4) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 4) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4)); + } + } + + + public (T1, T2, T3, T4) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5)>(new WhenAllPromise(task1, task2, task3, task4, task5), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 5) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 5) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 5) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 5) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 5) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5)); + } + } + + + public (T1, T2, T3, T4, T5) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 6) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 6) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 6) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 6) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 6) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 6) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6)); + } + } + + + public (T1, T2, T3, T4, T5, T6) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 7) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 8) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 9) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully() && task10.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult(), task10.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + T10 t10 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + static void TryInvokeContinuationT10(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t10 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 10) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully() && task10.Status.IsCompletedSuccessfully() && task11.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult(), task10.GetAwaiter().GetResult(), task11.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + T10 t10 = default; + T11 t11 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT10(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t10 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + static void TryInvokeContinuationT11(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t11 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 11) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully() && task10.Status.IsCompletedSuccessfully() && task11.Status.IsCompletedSuccessfully() && task12.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult(), task10.GetAwaiter().GetResult(), task11.GetAwaiter().GetResult(), task12.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + T10 t10 = default; + T11 t11 = default; + T12 t12 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT10(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t10 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT11(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t11 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + static void TryInvokeContinuationT12(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t12 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 12) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully() && task10.Status.IsCompletedSuccessfully() && task11.Status.IsCompletedSuccessfully() && task12.Status.IsCompletedSuccessfully() && task13.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult(), task10.GetAwaiter().GetResult(), task11.GetAwaiter().GetResult(), task12.GetAwaiter().GetResult(), task13.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + T10 t10 = default; + T11 t11 = default; + T12 t12 = default; + T13 t13 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task13.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT13(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT13(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT10(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t10 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT11(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t11 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT12(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t12 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + static void TryInvokeContinuationT13(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t13 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 13) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully() && task10.Status.IsCompletedSuccessfully() && task11.Status.IsCompletedSuccessfully() && task12.Status.IsCompletedSuccessfully() && task13.Status.IsCompletedSuccessfully() && task14.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult(), task10.GetAwaiter().GetResult(), task11.GetAwaiter().GetResult(), task12.GetAwaiter().GetResult(), task13.GetAwaiter().GetResult(), task14.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13, task14), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + T10 t10 = default; + T11 t11 = default; + T12 t12 = default; + T13 t13 = default; + T14 t14 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task13.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT13(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT13(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task14.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT14(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT14(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT10(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t10 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT11(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t11 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT12(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t12 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT13(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t13 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + static void TryInvokeContinuationT14(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t14 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 14) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)> WhenAll(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14, UniTask task15) + { + if (task1.Status.IsCompletedSuccessfully() && task2.Status.IsCompletedSuccessfully() && task3.Status.IsCompletedSuccessfully() && task4.Status.IsCompletedSuccessfully() && task5.Status.IsCompletedSuccessfully() && task6.Status.IsCompletedSuccessfully() && task7.Status.IsCompletedSuccessfully() && task8.Status.IsCompletedSuccessfully() && task9.Status.IsCompletedSuccessfully() && task10.Status.IsCompletedSuccessfully() && task11.Status.IsCompletedSuccessfully() && task12.Status.IsCompletedSuccessfully() && task13.Status.IsCompletedSuccessfully() && task14.Status.IsCompletedSuccessfully() && task15.Status.IsCompletedSuccessfully()) + { + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)>((task1.GetAwaiter().GetResult(), task2.GetAwaiter().GetResult(), task3.GetAwaiter().GetResult(), task4.GetAwaiter().GetResult(), task5.GetAwaiter().GetResult(), task6.GetAwaiter().GetResult(), task7.GetAwaiter().GetResult(), task8.GetAwaiter().GetResult(), task9.GetAwaiter().GetResult(), task10.GetAwaiter().GetResult(), task11.GetAwaiter().GetResult(), task12.GetAwaiter().GetResult(), task13.GetAwaiter().GetResult(), task14.GetAwaiter().GetResult(), task15.GetAwaiter().GetResult())); + } + + return new UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)>(new WhenAllPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13, task14, task15), 0); + } + + sealed class WhenAllPromise : IUniTaskSource<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)> + { + T1 t1 = default; + T2 t2 = default; + T3 t3 = default; + T4 t4 = default; + T5 t5 = default; + T6 t6 = default; + T7 t7 = default; + T8 t8 = default; + T9 t9 = default; + T10 t10 = default; + T11 t11 = default; + T12 t12 = default; + T13 t13 = default; + T14 t14 = default; + T15 t15 = default; + int completedCount; + UniTaskCompletionSourceCore<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)> core; + + public WhenAllPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14, UniTask task15) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task13.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT13(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT13(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task14.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT14(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT14(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task15.GetAwaiter(); + if (awaiter.IsCompleted) + { + TryInvokeContinuationT15(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT15(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t1 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT2(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t2 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT3(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t3 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT4(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t4 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT5(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t5 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT6(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t6 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT7(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t7 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT8(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t8 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT9(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t9 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT10(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t10 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT11(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t11 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT12(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t12 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT13(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t13 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT14(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t14 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + static void TryInvokeContinuationT15(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + self.t15 = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 15) + { + self.core.TrySetResult((self.t1, self.t2, self.t3, self.t4, self.t5, self.t6, self.t7, self.t8, self.t9, self.t10, self.t11, self.t12, self.t13, self.t14, self.t15)); + } + } + + + public (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.Generated.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.Generated.cs.meta new file mode 100644 index 00000000..40ed46cd --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.Generated.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5110117231c8a6d4095fd0cbd3f4c142 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.cs new file mode 100644 index 00000000..39f6a9ad --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.cs @@ -0,0 +1,237 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + public static UniTask WhenAll(params UniTask[] tasks) + { + if (tasks.Length == 0) + { + return UniTask.FromResult(Array.Empty()); + } + + return new UniTask(new WhenAllPromise(tasks, tasks.Length), 0); + } + + public static UniTask WhenAll(IEnumerable> tasks) + { + using (var span = ArrayPoolUtil.Materialize(tasks)) + { + var promise = new WhenAllPromise(span.Array, span.Length); // consumed array in constructor. + return new UniTask(promise, 0); + } + } + + public static UniTask WhenAll(params UniTask[] tasks) + { + if (tasks.Length == 0) + { + return UniTask.CompletedTask; + } + + return new UniTask(new WhenAllPromise(tasks, tasks.Length), 0); + } + + public static UniTask WhenAll(IEnumerable tasks) + { + using (var span = ArrayPoolUtil.Materialize(tasks)) + { + var promise = new WhenAllPromise(span.Array, span.Length); // consumed array in constructor. + return new UniTask(promise, 0); + } + } + + sealed class WhenAllPromise : IUniTaskSource + { + T[] result; + int completeCount; + UniTaskCompletionSourceCore core; // don't reset(called after GetResult, will invoke TrySetException.) + + public WhenAllPromise(UniTask[] tasks, int tasksLength) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completeCount = 0; + + if (tasksLength == 0) + { + this.result = Array.Empty(); + core.TrySetResult(result); + return; + } + + this.result = new T[tasksLength]; + + for (int i = 0; i < tasksLength; i++) + { + UniTask.Awaiter awaiter; + try + { + awaiter = tasks[i].GetAwaiter(); + } + catch (Exception ex) + { + core.TrySetException(ex); + continue; + } + + if (awaiter.IsCompleted) + { + TryInvokeContinuation(this, awaiter, i); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter, int>)state) + { + TryInvokeContinuation(t.Item1, t.Item2, t.Item3); + } + }, StateTuple.Create(this, awaiter, i)); + } + } + } + + static void TryInvokeContinuation(WhenAllPromise self, in UniTask.Awaiter awaiter, int i) + { + try + { + self.result[i] = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completeCount) == self.result.Length) + { + self.core.TrySetResult(self.result); + } + } + + public T[] GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + sealed class WhenAllPromise : IUniTaskSource + { + int completeCount; + int tasksLength; + UniTaskCompletionSourceCore core; // don't reset(called after GetResult, will invoke TrySetException.) + + public WhenAllPromise(UniTask[] tasks, int tasksLength) + { + TaskTracker.TrackActiveTask(this, 3); + + this.tasksLength = tasksLength; + this.completeCount = 0; + + if (tasksLength == 0) + { + core.TrySetResult(AsyncUnit.Default); + return; + } + + for (int i = 0; i < tasksLength; i++) + { + UniTask.Awaiter awaiter; + try + { + awaiter = tasks[i].GetAwaiter(); + } + catch (Exception ex) + { + core.TrySetException(ex); + continue; + } + + if (awaiter.IsCompleted) + { + TryInvokeContinuation(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple)state) + { + TryInvokeContinuation(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuation(WhenAllPromise self, in UniTask.Awaiter awaiter) + { + try + { + awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completeCount) == self.tasksLength) + { + self.core.TrySetResult(AsyncUnit.Default); + } + } + + public void GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.cs.meta new file mode 100644 index 00000000..0366aa87 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAll.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 355997a305ba64248822eec34998a1a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.Generated.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.Generated.cs new file mode 100644 index 00000000..09b98e62 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.Generated.cs @@ -0,0 +1,5060 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2)> WhenAny(UniTask task1, UniTask task2) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2)>(new WhenAnyPromise(task1, task2), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result)); + } + } + + + public (int, T1 result1, T2 result2) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3)> WhenAny(UniTask task1, UniTask task2, UniTask task3) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3)>(new WhenAnyPromise(task1, task2, task3), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4)>(new WhenAnyPromise(task1, task2, task3, task4), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5)>(new WhenAnyPromise(task1, task2, task3, task4, task5), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT10(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T10 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((9, default, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT10(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T10 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((9, default, default, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT11(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T11 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((10, default, default, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT10(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T10 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((9, default, default, default, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT11(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T11 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((10, default, default, default, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT12(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T12 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((11, default, default, default, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task13.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT13(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT13(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT10(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T10 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((9, default, default, default, default, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT11(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T11 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((10, default, default, default, default, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT12(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T12 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((11, default, default, default, default, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT13(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T13 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((12, default, default, default, default, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13, task14), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task13.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT13(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT13(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task14.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT14(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT14(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT10(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T10 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((9, default, default, default, default, default, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT11(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T11 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((10, default, default, default, default, default, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT12(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T12 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((11, default, default, default, default, default, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT13(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T13 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((12, default, default, default, default, default, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT14(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T14 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((13, default, default, default, default, default, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + public static UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14, T15 result15)> WhenAny(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14, UniTask task15) + { + return new UniTask<(int winArgumentIndex, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14, T15 result15)>(new WhenAnyPromise(task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13, task14, task15), 0); + } + + sealed class WhenAnyPromise : IUniTaskSource<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14, T15 result15)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14, T15 result15)> core; + + public WhenAnyPromise(UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14, UniTask task15) + { + TaskTracker.TrackActiveTask(this, 3); + + this.completedCount = 0; + { + var awaiter = task1.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT1(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT1(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task2.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT2(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT2(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task3.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT3(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT3(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task4.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT4(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT4(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task5.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT5(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT5(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task6.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT6(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT6(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task7.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT7(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT7(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task8.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT8(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT8(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task9.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT9(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT9(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task10.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT10(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT10(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task11.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT11(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT11(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task12.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT12(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT12(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task13.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT13(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT13(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task14.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT14(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT14(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + { + var awaiter = task15.GetAwaiter(); + + if (awaiter.IsCompleted) + { + TryInvokeContinuationT15(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryInvokeContinuationT15(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryInvokeContinuationT1(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T1 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((0, result, default, default, default, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT2(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T2 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((1, default, result, default, default, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT3(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T3 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((2, default, default, result, default, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT4(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T4 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((3, default, default, default, result, default, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT5(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T5 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((4, default, default, default, default, result, default, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT6(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T6 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((5, default, default, default, default, default, result, default, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT7(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T7 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((6, default, default, default, default, default, default, result, default, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT8(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T8 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((7, default, default, default, default, default, default, default, result, default, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT9(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T9 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((8, default, default, default, default, default, default, default, default, result, default, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT10(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T10 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((9, default, default, default, default, default, default, default, default, default, result, default, default, default, default, default)); + } + } + + static void TryInvokeContinuationT11(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T11 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((10, default, default, default, default, default, default, default, default, default, default, result, default, default, default, default)); + } + } + + static void TryInvokeContinuationT12(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T12 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((11, default, default, default, default, default, default, default, default, default, default, default, result, default, default, default)); + } + } + + static void TryInvokeContinuationT13(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T13 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((12, default, default, default, default, default, default, default, default, default, default, default, default, result, default, default)); + } + } + + static void TryInvokeContinuationT14(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T14 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((13, default, default, default, default, default, default, default, default, default, default, default, default, default, result, default)); + } + } + + static void TryInvokeContinuationT15(WhenAnyPromise self, in UniTask.Awaiter awaiter) + { + T15 result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((14, default, default, default, default, default, default, default, default, default, default, default, default, default, default, result)); + } + } + + + public (int, T1 result1, T2 result2, T3 result3, T4 result4, T5 result5, T6 result6, T7 result7, T8 result8, T9 result9, T10 result10, T11 result11, T12 result12, T13 result13, T14 result14, T15 result15) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.Generated.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.Generated.cs.meta new file mode 100644 index 00000000..49a2c3fd --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.Generated.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 13d604ac281570c4eac9962429f19ca9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.cs new file mode 100644 index 00000000..09eb32d7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.cs @@ -0,0 +1,359 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + public static UniTask<(bool hasResultLeft, T result)> WhenAny(UniTask leftTask, UniTask rightTask) + { + return new UniTask<(bool, T)>(new WhenAnyLRPromise(leftTask, rightTask), 0); + } + + public static UniTask<(int winArgumentIndex, T result)> WhenAny(params UniTask[] tasks) + { + return new UniTask<(int, T)>(new WhenAnyPromise(tasks, tasks.Length), 0); + } + + public static UniTask<(int winArgumentIndex, T result)> WhenAny(IEnumerable> tasks) + { + using (var span = ArrayPoolUtil.Materialize(tasks)) + { + return new UniTask<(int, T)>(new WhenAnyPromise(span.Array, span.Length), 0); + } + } + + /// Return value is winArgumentIndex + public static UniTask WhenAny(params UniTask[] tasks) + { + return new UniTask(new WhenAnyPromise(tasks, tasks.Length), 0); + } + + /// Return value is winArgumentIndex + public static UniTask WhenAny(IEnumerable tasks) + { + using (var span = ArrayPoolUtil.Materialize(tasks)) + { + return new UniTask(new WhenAnyPromise(span.Array, span.Length), 0); + } + } + + sealed class WhenAnyLRPromise : IUniTaskSource<(bool, T)> + { + int completedCount; + UniTaskCompletionSourceCore<(bool, T)> core; + + public WhenAnyLRPromise(UniTask leftTask, UniTask rightTask) + { + TaskTracker.TrackActiveTask(this, 3); + + { + UniTask.Awaiter awaiter; + try + { + awaiter = leftTask.GetAwaiter(); + } + catch (Exception ex) + { + core.TrySetException(ex); + goto RIGHT; + } + + if (awaiter.IsCompleted) + { + TryLeftInvokeContinuation(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryLeftInvokeContinuation(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + RIGHT: + { + UniTask.Awaiter awaiter; + try + { + awaiter = rightTask.GetAwaiter(); + } + catch (Exception ex) + { + core.TrySetException(ex); + return; + } + + if (awaiter.IsCompleted) + { + TryRightInvokeContinuation(this, awaiter); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter>)state) + { + TryRightInvokeContinuation(t.Item1, t.Item2); + } + }, StateTuple.Create(this, awaiter)); + } + } + } + + static void TryLeftInvokeContinuation(WhenAnyLRPromise self, in UniTask.Awaiter awaiter) + { + T result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((true, result)); + } + } + + static void TryRightInvokeContinuation(WhenAnyLRPromise self, in UniTask.Awaiter awaiter) + { + try + { + awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((false, default)); + } + } + + public (bool, T) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + + sealed class WhenAnyPromise : IUniTaskSource<(int, T)> + { + int completedCount; + UniTaskCompletionSourceCore<(int, T)> core; + + public WhenAnyPromise(UniTask[] tasks, int tasksLength) + { + if (tasksLength == 0) + { + throw new ArgumentException("The tasks argument contains no tasks."); + } + + TaskTracker.TrackActiveTask(this, 3); + + for (int i = 0; i < tasksLength; i++) + { + UniTask.Awaiter awaiter; + try + { + awaiter = tasks[i].GetAwaiter(); + } + catch (Exception ex) + { + core.TrySetException(ex); + continue; // consume others. + } + + if (awaiter.IsCompleted) + { + TryInvokeContinuation(this, awaiter, i); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple, UniTask.Awaiter, int>)state) + { + TryInvokeContinuation(t.Item1, t.Item2, t.Item3); + } + }, StateTuple.Create(this, awaiter, i)); + } + } + } + + static void TryInvokeContinuation(WhenAnyPromise self, in UniTask.Awaiter awaiter, int i) + { + T result; + try + { + result = awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult((i, result)); + } + } + + public (int, T) GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + sealed class WhenAnyPromise : IUniTaskSource + { + int completedCount; + UniTaskCompletionSourceCore core; + + public WhenAnyPromise(UniTask[] tasks, int tasksLength) + { + if (tasksLength == 0) + { + throw new ArgumentException("The tasks argument contains no tasks."); + } + + TaskTracker.TrackActiveTask(this, 3); + + for (int i = 0; i < tasksLength; i++) + { + UniTask.Awaiter awaiter; + try + { + awaiter = tasks[i].GetAwaiter(); + } + catch (Exception ex) + { + core.TrySetException(ex); + continue; // consume others. + } + + if (awaiter.IsCompleted) + { + TryInvokeContinuation(this, awaiter, i); + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple)state) + { + TryInvokeContinuation(t.Item1, t.Item2, t.Item3); + } + }, StateTuple.Create(this, awaiter, i)); + } + } + } + + static void TryInvokeContinuation(WhenAnyPromise self, in UniTask.Awaiter awaiter, int i) + { + try + { + awaiter.GetResult(); + } + catch (Exception ex) + { + self.core.TrySetException(ex); + return; + } + + if (Interlocked.Increment(ref self.completedCount) == 1) + { + self.core.TrySetResult(i); + } + } + + public int GetResult(short token) + { + TaskTracker.RemoveTracking(this); + GC.SuppressFinalize(this); + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.cs.meta new file mode 100644 index 00000000..c10f7621 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenAny.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c32578978c37eaf41bdd90e1b034637d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenEach.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenEach.cs new file mode 100644 index 00000000..a3f0923e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenEach.cs @@ -0,0 +1,183 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + public static IUniTaskAsyncEnumerable> WhenEach(IEnumerable> tasks) + { + return new WhenEachEnumerable(tasks); + } + + public static IUniTaskAsyncEnumerable> WhenEach(params UniTask[] tasks) + { + return new WhenEachEnumerable(tasks); + } + } + + public readonly struct WhenEachResult + { + public T Result { get; } + public Exception Exception { get; } + + //[MemberNotNullWhen(false, nameof(Exception))] + public bool IsCompletedSuccessfully => Exception == null; + + //[MemberNotNullWhen(true, nameof(Exception))] + public bool IsFaulted => Exception != null; + + public WhenEachResult(T result) + { + this.Result = result; + this.Exception = null; + } + + public WhenEachResult(Exception exception) + { + if (exception == null) throw new ArgumentNullException(nameof(exception)); + this.Result = default; + this.Exception = exception; + } + + public void TryThrow() + { + if (IsFaulted) + { + ExceptionDispatchInfo.Capture(Exception).Throw(); + } + } + + public T GetResult() + { + if (IsFaulted) + { + ExceptionDispatchInfo.Capture(Exception).Throw(); + } + return Result; + } + + public override string ToString() + { + if (IsCompletedSuccessfully) + { + return Result?.ToString() ?? ""; + } + else + { + return $"Exception{{{Exception.Message}}}"; + } + } + } + + internal enum WhenEachState : byte + { + NotRunning, + Running, + Completed + } + + internal sealed class WhenEachEnumerable : IUniTaskAsyncEnumerable> + { + IEnumerable> source; + + public WhenEachEnumerable(IEnumerable> source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + sealed class Enumerator : IUniTaskAsyncEnumerator> + { + readonly IEnumerable> source; + CancellationToken cancellationToken; + + Channel> channel; + IUniTaskAsyncEnumerator> channelEnumerator; + int completeCount; + WhenEachState state; + + public Enumerator(IEnumerable> source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public WhenEachResult Current => channelEnumerator.Current; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (state == WhenEachState.NotRunning) + { + state = WhenEachState.Running; + channel = Channel.CreateSingleConsumerUnbounded>(); + channelEnumerator = channel.Reader.ReadAllAsync().GetAsyncEnumerator(cancellationToken); + + if (source is UniTask[] array) + { + ConsumeAll(this, array, array.Length); + } + else + { + using (var rentArray = ArrayPoolUtil.Materialize(source)) + { + ConsumeAll(this, rentArray.Array, rentArray.Length); + } + } + } + + return channelEnumerator.MoveNextAsync(); + } + + static void ConsumeAll(Enumerator self, UniTask[] array, int length) + { + for (int i = 0; i < length; i++) + { + RunWhenEachTask(self, array[i], length).Forget(); + } + } + + static async UniTaskVoid RunWhenEachTask(Enumerator self, UniTask task, int length) + { + try + { + var result = await task; + self.channel.Writer.TryWrite(new WhenEachResult(result)); + } + catch (Exception ex) + { + self.channel.Writer.TryWrite(new WhenEachResult(ex)); + } + + if (Interlocked.Increment(ref self.completeCount) == length) + { + self.state = WhenEachState.Completed; + self.channel.Writer.TryComplete(); + } + } + + public async UniTask DisposeAsync() + { + if (channelEnumerator != null) + { + await channelEnumerator.DisposeAsync(); + } + + if (state != WhenEachState.Completed) + { + state = WhenEachState.Completed; + channel.Writer.TryComplete(new OperationCanceledException()); + } + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenEach.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenEach.cs.meta new file mode 100644 index 00000000..ca2b38eb --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.WhenEach.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7cac24fdda5112047a1cd3dd66b542c4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.asmdef b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.asmdef new file mode 100644 index 00000000..a5c594d7 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.asmdef @@ -0,0 +1,45 @@ +{ + "name": "UniTask", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.modules.assetbundle", + "expression": "", + "define": "UNITASK_ASSETBUNDLE_SUPPORT" + }, + { + "name": "com.unity.modules.physics", + "expression": "", + "define": "UNITASK_PHYSICS_SUPPORT" + }, + { + "name": "com.unity.modules.physics2d", + "expression": "", + "define": "UNITASK_PHYSICS2D_SUPPORT" + }, + { + "name": "com.unity.modules.particlesystem", + "expression": "", + "define": "UNITASK_PARTICLESYSTEM_SUPPORT" + }, + { + "name": "com.unity.ugui", + "expression": "", + "define": "UNITASK_UGUI_SUPPORT" + }, + { + "name": "com.unity.modules.unitywebrequest", + "expression": "", + "define": "UNITASK_WEBREQUEST_SUPPORT" + } + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.asmdef.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.asmdef.meta new file mode 100644 index 00000000..e497045e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f51ebe6a0ceec4240a699833d6309b23 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.cs new file mode 100644 index 00000000..56a8d1fb --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.cs @@ -0,0 +1,711 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable CS0436 + +#if UNITASK_NETCORE || UNITY_2022_3_OR_NEWER +#define SUPPORT_VALUETASK +#endif + +using Cysharp.Threading.Tasks.CompilerServices; +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; + +namespace Cysharp.Threading.Tasks +{ + internal static class AwaiterActions + { + internal static readonly Action InvokeContinuationDelegate = Continuation; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static void Continuation(object state) + { + ((Action)state).Invoke(); + } + } + + /// + /// Lightweight unity specified task-like object. + /// + [AsyncMethodBuilder(typeof(AsyncUniTaskMethodBuilder))] + [StructLayout(LayoutKind.Auto)] + public readonly partial struct UniTask + { + readonly IUniTaskSource source; + readonly short token; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTask(IUniTaskSource source, short token) + { + this.source = source; + this.token = token; + } + + public UniTaskStatus Status + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (source == null) return UniTaskStatus.Succeeded; + return source.GetStatus(token); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Awaiter GetAwaiter() + { + return new Awaiter(this); + } + + /// + /// returns (bool IsCanceled) instead of throws OperationCanceledException. + /// + public UniTask SuppressCancellationThrow() + { + var status = Status; + if (status == UniTaskStatus.Succeeded) return CompletedTasks.False; + if (status == UniTaskStatus.Canceled) return CompletedTasks.True; + return new UniTask(new IsCanceledSource(source), token); + } + +#if SUPPORT_VALUETASK + + public static implicit operator System.Threading.Tasks.ValueTask(in UniTask self) + { + if (self.source == null) + { + return default; + } + +#if (UNITASK_NETCORE && NETSTANDARD2_0) + return self.AsValueTask(); +#else + return new System.Threading.Tasks.ValueTask(self.source, self.token); +#endif + } + +#endif + + public override string ToString() + { + if (source == null) return "()"; + return "(" + source.UnsafeGetStatus() + ")"; + } + + /// + /// Memoizing inner IValueTaskSource. The result UniTask can await multiple. + /// + public UniTask Preserve() + { + if (source == null) + { + return this; + } + else + { + return new UniTask(new MemoizeSource(source), token); + } + } + + public UniTask AsAsyncUnitUniTask() + { + if (this.source == null) return CompletedTasks.AsyncUnit; + + var status = this.source.GetStatus(this.token); + if (status.IsCompletedSuccessfully()) + { + this.source.GetResult(this.token); + return CompletedTasks.AsyncUnit; + } + else if (this.source is IUniTaskSource asyncUnitSource) + { + return new UniTask(asyncUnitSource, this.token); + } + + return new UniTask(new AsyncUnitSource(this.source), this.token); + } + + sealed class AsyncUnitSource : IUniTaskSource + { + readonly IUniTaskSource source; + + public AsyncUnitSource(IUniTaskSource source) + { + this.source = source; + } + + public AsyncUnit GetResult(short token) + { + source.GetResult(token); + return AsyncUnit.Default; + } + + public UniTaskStatus GetStatus(short token) + { + return source.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + source.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return source.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + } + + sealed class IsCanceledSource : IUniTaskSource + { + readonly IUniTaskSource source; + + public IsCanceledSource(IUniTaskSource source) + { + this.source = source; + } + + public bool GetResult(short token) + { + if (source.GetStatus(token) == UniTaskStatus.Canceled) + { + return true; + } + + source.GetResult(token); + return false; + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return source.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return source.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + source.OnCompleted(continuation, state, token); + } + } + + sealed class MemoizeSource : IUniTaskSource + { + IUniTaskSource source; + ExceptionDispatchInfo exception; + UniTaskStatus status; + + public MemoizeSource(IUniTaskSource source) + { + this.source = source; + } + + public void GetResult(short token) + { + if (source == null) + { + if (exception != null) + { + exception.Throw(); + } + } + else + { + try + { + source.GetResult(token); + status = UniTaskStatus.Succeeded; + } + catch (Exception ex) + { + exception = ExceptionDispatchInfo.Capture(ex); + if (ex is OperationCanceledException) + { + status = UniTaskStatus.Canceled; + } + else + { + status = UniTaskStatus.Faulted; + } + throw; + } + finally + { + source = null; + } + } + } + + public UniTaskStatus GetStatus(short token) + { + if (source == null) + { + return status; + } + + return source.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + if (source == null) + { + continuation(state); + } + else + { + source.OnCompleted(continuation, state, token); + } + } + + public UniTaskStatus UnsafeGetStatus() + { + if (source == null) + { + return status; + } + + return source.UnsafeGetStatus(); + } + } + + public readonly struct Awaiter : ICriticalNotifyCompletion + { + readonly UniTask task; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Awaiter(in UniTask task) + { + this.task = task; + } + + public bool IsCompleted + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return task.Status.IsCompleted(); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GetResult() + { + if (task.source == null) return; + task.source.GetResult(task.token); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action continuation) + { + if (task.source == null) + { + continuation(); + } + else + { + task.source.OnCompleted(AwaiterActions.InvokeContinuationDelegate, continuation, task.token); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeOnCompleted(Action continuation) + { + if (task.source == null) + { + continuation(); + } + else + { + task.source.OnCompleted(AwaiterActions.InvokeContinuationDelegate, continuation, task.token); + } + } + + /// + /// If register manually continuation, you can use it instead of for compiler OnCompleted methods. + /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SourceOnCompleted(Action continuation, object state) + { + if (task.source == null) + { + continuation(state); + } + else + { + task.source.OnCompleted(continuation, state, task.token); + } + } + } + } + + /// + /// Lightweight unity specified task-like object. + /// + [AsyncMethodBuilder(typeof(AsyncUniTaskMethodBuilder<>))] + [StructLayout(LayoutKind.Auto)] + public readonly struct UniTask + { + readonly IUniTaskSource source; + readonly T result; + readonly short token; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTask(T result) + { + this.source = default; + this.token = default; + this.result = result; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTask(IUniTaskSource source, short token) + { + this.source = source; + this.token = token; + this.result = default; + } + + public UniTaskStatus Status + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return (source == null) ? UniTaskStatus.Succeeded : source.GetStatus(token); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Awaiter GetAwaiter() + { + return new Awaiter(this); + } + + /// + /// Memoizing inner IValueTaskSource. The result UniTask can await multiple. + /// + public UniTask Preserve() + { + if (source == null) + { + return this; + } + else + { + return new UniTask(new MemoizeSource(source), token); + } + } + + public UniTask AsUniTask() + { + if (this.source == null) return UniTask.CompletedTask; + + var status = this.source.GetStatus(this.token); + if (status.IsCompletedSuccessfully()) + { + this.source.GetResult(this.token); + return UniTask.CompletedTask; + } + + // Converting UniTask -> UniTask is zero overhead. + return new UniTask(this.source, this.token); + } + + public static implicit operator UniTask(UniTask self) + { + return self.AsUniTask(); + } + +#if SUPPORT_VALUETASK + + public static implicit operator System.Threading.Tasks.ValueTask(in UniTask self) + { + if (self.source == null) + { + return new System.Threading.Tasks.ValueTask(self.result); + } + +#if (UNITASK_NETCORE && NETSTANDARD2_0) + return self.AsValueTask(); +#else + return new System.Threading.Tasks.ValueTask(self.source, self.token); +#endif + } + +#endif + + /// + /// returns (bool IsCanceled, T Result) instead of throws OperationCanceledException. + /// + public UniTask<(bool IsCanceled, T Result)> SuppressCancellationThrow() + { + if (source == null) + { + return new UniTask<(bool IsCanceled, T Result)>((false, result)); + } + + return new UniTask<(bool, T)>(new IsCanceledSource(source), token); + } + + public override string ToString() + { + return (this.source == null) ? result?.ToString() + : "(" + this.source.UnsafeGetStatus() + ")"; + } + + sealed class IsCanceledSource : IUniTaskSource<(bool, T)> + { + readonly IUniTaskSource source; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IsCanceledSource(IUniTaskSource source) + { + this.source = source; + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (bool, T) GetResult(short token) + { + if (source.GetStatus(token) == UniTaskStatus.Canceled) + { + return (true, default); + } + + var result = source.GetResult(token); + return (false, result); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTaskStatus GetStatus(short token) + { + return source.GetStatus(token); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTaskStatus UnsafeGetStatus() + { + return source.UnsafeGetStatus(); + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action continuation, object state, short token) + { + source.OnCompleted(continuation, state, token); + } + } + + sealed class MemoizeSource : IUniTaskSource + { + IUniTaskSource source; + T result; + ExceptionDispatchInfo exception; + UniTaskStatus status; + + public MemoizeSource(IUniTaskSource source) + { + this.source = source; + } + + public T GetResult(short token) + { + if (source == null) + { + if (exception != null) + { + exception.Throw(); + } + return result; + } + else + { + try + { + result = source.GetResult(token); + status = UniTaskStatus.Succeeded; + return result; + } + catch (Exception ex) + { + exception = ExceptionDispatchInfo.Capture(ex); + if (ex is OperationCanceledException) + { + status = UniTaskStatus.Canceled; + } + else + { + status = UniTaskStatus.Faulted; + } + throw; + } + finally + { + source = null; + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + if (source == null) + { + return status; + } + + return source.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + if (source == null) + { + continuation(state); + } + else + { + source.OnCompleted(continuation, state, token); + } + } + + public UniTaskStatus UnsafeGetStatus() + { + if (source == null) + { + return status; + } + + return source.UnsafeGetStatus(); + } + } + + public readonly struct Awaiter : ICriticalNotifyCompletion + { + readonly UniTask task; + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Awaiter(in UniTask task) + { + this.task = task; + } + + public bool IsCompleted + { + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return task.Status.IsCompleted(); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T GetResult() + { + var s = task.source; + if (s == null) + { + return task.result; + } + else + { + return s.GetResult(task.token); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action continuation) + { + var s = task.source; + if (s == null) + { + continuation(); + } + else + { + s.OnCompleted(AwaiterActions.InvokeContinuationDelegate, continuation, task.token); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeOnCompleted(Action continuation) + { + var s = task.source; + if (s == null) + { + continuation(); + } + else + { + s.OnCompleted(AwaiterActions.InvokeContinuationDelegate, continuation, task.token); + } + } + + /// + /// If register manually continuation, you can use it instead of for compiler OnCompleted methods. + /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SourceOnCompleted(Action continuation, object state) + { + var s = task.source; + if (s == null) + { + continuation(state); + } + else + { + s.OnCompleted(continuation, state, task.token); + } + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.cs.meta new file mode 100644 index 00000000..04eb6b64 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8947adf23181ff04db73829df217ca94 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskCompletionSource.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskCompletionSource.cs new file mode 100644 index 00000000..bf2d054b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskCompletionSource.cs @@ -0,0 +1,944 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public interface IResolvePromise + { + bool TrySetResult(); + } + + public interface IResolvePromise + { + bool TrySetResult(T value); + } + + public interface IRejectPromise + { + bool TrySetException(Exception exception); + } + + public interface ICancelPromise + { + bool TrySetCanceled(CancellationToken cancellationToken = default); + } + + public interface IPromise : IResolvePromise, IRejectPromise, ICancelPromise + { + } + + public interface IPromise : IResolvePromise, IRejectPromise, ICancelPromise + { + } + + internal class ExceptionHolder + { + ExceptionDispatchInfo exception; + bool calledGet = false; + + public ExceptionHolder(ExceptionDispatchInfo exception) + { + this.exception = exception; + } + + public ExceptionDispatchInfo GetException() + { + if (!calledGet) + { + calledGet = true; + GC.SuppressFinalize(this); + } + return exception; + } + + ~ExceptionHolder() + { + if (!calledGet) + { + UniTaskScheduler.PublishUnobservedTaskException(exception.SourceException); + } + } + } + + [StructLayout(LayoutKind.Auto)] + public struct UniTaskCompletionSourceCore + { + // Struct Size: TResult + (8 + 2 + 1 + 1 + 8 + 8) + + TResult result; + object error; // ExceptionHolder or OperationCanceledException + short version; + bool hasUnhandledError; + int completedCount; // 0: completed == false + Action continuation; + object continuationState; + + [DebuggerHidden] + public void Reset() + { + ReportUnhandledError(); + + unchecked + { + version += 1; // incr version. + } + completedCount = 0; + result = default; + error = null; + hasUnhandledError = false; + continuation = null; + continuationState = null; + } + + void ReportUnhandledError() + { + if (hasUnhandledError) + { + try + { + if (error is OperationCanceledException oc) + { + UniTaskScheduler.PublishUnobservedTaskException(oc); + } + else if (error is ExceptionHolder e) + { + UniTaskScheduler.PublishUnobservedTaskException(e.GetException().SourceException); + } + } + catch + { + } + } + } + + internal void MarkHandled() + { + hasUnhandledError = false; + } + + /// Completes with a successful result. + /// The result. + [DebuggerHidden] + public bool TrySetResult(TResult result) + { + if (Interlocked.Increment(ref completedCount) == 1) + { + // setup result + this.result = result; + + if (continuation != null || Interlocked.CompareExchange(ref this.continuation, UniTaskCompletionSourceCoreShared.s_sentinel, null) != null) + { + continuation(continuationState); + } + return true; + } + + return false; + } + + /// Completes with an error. + /// The exception. + [DebuggerHidden] + public bool TrySetException(Exception error) + { + if (Interlocked.Increment(ref completedCount) == 1) + { + // setup result + this.hasUnhandledError = true; + if (error is OperationCanceledException) + { + this.error = error; + } + else + { + this.error = new ExceptionHolder(ExceptionDispatchInfo.Capture(error)); + } + + if (continuation != null || Interlocked.CompareExchange(ref this.continuation, UniTaskCompletionSourceCoreShared.s_sentinel, null) != null) + { + continuation(continuationState); + } + return true; + } + + return false; + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + if (Interlocked.Increment(ref completedCount) == 1) + { + // setup result + this.hasUnhandledError = true; + this.error = new OperationCanceledException(cancellationToken); + + if (continuation != null || Interlocked.CompareExchange(ref this.continuation, UniTaskCompletionSourceCoreShared.s_sentinel, null) != null) + { + continuation(continuationState); + } + return true; + } + + return false; + } + + /// Gets the operation version. + [DebuggerHidden] + public short Version => version; + + /// Gets the status of the operation. + /// Opaque value that was provided to the 's constructor. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTaskStatus GetStatus(short token) + { + ValidateToken(token); + return (continuation == null || (completedCount == 0)) ? UniTaskStatus.Pending + : (error == null) ? UniTaskStatus.Succeeded + : (error is OperationCanceledException) ? UniTaskStatus.Canceled + : UniTaskStatus.Faulted; + } + + /// Gets the status of the operation without token validation. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UniTaskStatus UnsafeGetStatus() + { + return (continuation == null || (completedCount == 0)) ? UniTaskStatus.Pending + : (error == null) ? UniTaskStatus.Succeeded + : (error is OperationCanceledException) ? UniTaskStatus.Canceled + : UniTaskStatus.Faulted; + } + + /// Gets the result of the operation. + /// Opaque value that was provided to the 's constructor. + // [StackTraceHidden] + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TResult GetResult(short token) + { + ValidateToken(token); + if (completedCount == 0) + { + throw new InvalidOperationException("Not yet completed, UniTask only allow to use await."); + } + + if (error != null) + { + hasUnhandledError = false; + if (error is OperationCanceledException oce) + { + throw oce; + } + else if (error is ExceptionHolder eh) + { + eh.GetException().Throw(); + } + + throw new InvalidOperationException("Critical: invalid exception type was held."); + } + + return result; + } + + /// Schedules the continuation action for this operation. + /// The continuation to invoke when the operation has completed. + /// The state object to pass to when it's invoked. + /// Opaque value that was provided to the 's constructor. + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted(Action continuation, object state, short token /*, ValueTaskSourceOnCompletedFlags flags */) + { + if (continuation == null) + { + throw new ArgumentNullException(nameof(continuation)); + } + ValidateToken(token); + + /* no use ValueTaskSourceOnCOmpletedFlags, always no capture ExecutionContext and SynchronizationContext. */ + + /* + PatternA: GetStatus=Pending => OnCompleted => TrySet*** => GetResult + PatternB: TrySet*** => GetStatus=!Pending => GetResult + PatternC: GetStatus=Pending => TrySet/OnCompleted(race condition) => GetResult + C.1: win OnCompleted -> TrySet invoke saved continuation + C.2: win TrySet -> should invoke continuation here. + */ + + // not set continuation yet. + object oldContinuation = this.continuation; + if (oldContinuation == null) + { + continuationState = state; + oldContinuation = Interlocked.CompareExchange(ref this.continuation, continuation, null); + } + + if (oldContinuation != null) + { + // already running continuation in TrySet. + // It will cause call OnCompleted multiple time, invalid. + if (!ReferenceEquals(oldContinuation, UniTaskCompletionSourceCoreShared.s_sentinel)) + { + throw new InvalidOperationException("Already continuation registered, can not await twice or get Status after await."); + } + + continuation(state); + } + } + + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ValidateToken(short token) + { + if (token != version) + { + throw new InvalidOperationException("Token version is not matched, can not await twice or get Status after await."); + } + } + } + + internal static class UniTaskCompletionSourceCoreShared // separated out of generic to avoid unnecessary duplication + { + internal static readonly Action s_sentinel = CompletionSentinel; + + private static void CompletionSentinel(object _) // named method to aid debugging + { + throw new InvalidOperationException("The sentinel delegate should never be invoked."); + } + } + + public class AutoResetUniTaskCompletionSource : IUniTaskSource, ITaskPoolNode, IPromise + { + static TaskPool pool; + AutoResetUniTaskCompletionSource nextNode; + public ref AutoResetUniTaskCompletionSource NextNode => ref nextNode; + + static AutoResetUniTaskCompletionSource() + { + TaskPool.RegisterSizeGetter(typeof(AutoResetUniTaskCompletionSource), () => pool.Size); + } + + UniTaskCompletionSourceCore core; + short version; + + AutoResetUniTaskCompletionSource() + { + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource Create() + { + if (!pool.TryPop(out var result)) + { + result = new AutoResetUniTaskCompletionSource(); + } + result.version = result.core.Version; + TaskTracker.TrackActiveTask(result, 2); + return result; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource CreateFromCanceled(CancellationToken cancellationToken, out short token) + { + var source = Create(); + source.TrySetCanceled(cancellationToken); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource CreateFromException(Exception exception, out short token) + { + var source = Create(); + source.TrySetException(exception); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource CreateCompleted(out short token) + { + var source = Create(); + source.TrySetResult(); + token = source.core.Version; + return source; + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, core.Version); + } + } + + [DebuggerHidden] + public bool TrySetResult() + { + return version == core.Version && core.TrySetResult(AsyncUnit.Default); + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + return version == core.Version && core.TrySetCanceled(cancellationToken); + } + + [DebuggerHidden] + public bool TrySetException(Exception exception) + { + return version == core.Version && core.TrySetException(exception); + } + + [DebuggerHidden] + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + [DebuggerHidden] + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + return pool.TryPush(this); + } + } + + public class AutoResetUniTaskCompletionSource : IUniTaskSource, ITaskPoolNode>, IPromise + { + static TaskPool> pool; + AutoResetUniTaskCompletionSource nextNode; + public ref AutoResetUniTaskCompletionSource NextNode => ref nextNode; + + static AutoResetUniTaskCompletionSource() + { + TaskPool.RegisterSizeGetter(typeof(AutoResetUniTaskCompletionSource), () => pool.Size); + } + + UniTaskCompletionSourceCore core; + short version; + + AutoResetUniTaskCompletionSource() + { + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource Create() + { + if (!pool.TryPop(out var result)) + { + result = new AutoResetUniTaskCompletionSource(); + } + result.version = result.core.Version; + TaskTracker.TrackActiveTask(result, 2); + return result; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource CreateFromCanceled(CancellationToken cancellationToken, out short token) + { + var source = Create(); + source.TrySetCanceled(cancellationToken); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource CreateFromException(Exception exception, out short token) + { + var source = Create(); + source.TrySetException(exception); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSource CreateFromResult(T result, out short token) + { + var source = Create(); + source.TrySetResult(result); + token = source.core.Version; + return source; + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, core.Version); + } + } + + [DebuggerHidden] + public bool TrySetResult(T result) + { + return version == core.Version && core.TrySetResult(result); + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + return version == core.Version && core.TrySetCanceled(cancellationToken); + } + + [DebuggerHidden] + public bool TrySetException(Exception exception) + { + return version == core.Version && core.TrySetException(exception); + } + + [DebuggerHidden] + public T GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + [DebuggerHidden] + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + [DebuggerHidden] + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + return pool.TryPush(this); + } + } + + public class UniTaskCompletionSource : IUniTaskSource, IPromise + { + CancellationToken cancellationToken; + ExceptionHolder exception; + object gate; + Action singleContinuation; + object singleState; + List<(Action, object)> secondaryContinuationList; + + int intStatus; // UniTaskStatus + bool handled = false; + + public UniTaskCompletionSource() + { + TaskTracker.TrackActiveTask(this, 2); + } + + [DebuggerHidden] + internal void MarkHandled() + { + if (!handled) + { + handled = true; + TaskTracker.RemoveTracking(this); + } + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, 0); + } + } + + [DebuggerHidden] + public bool TrySetResult() + { + return TrySignalCompletion(UniTaskStatus.Succeeded); + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + if (UnsafeGetStatus() != UniTaskStatus.Pending) return false; + + this.cancellationToken = cancellationToken; + return TrySignalCompletion(UniTaskStatus.Canceled); + } + + [DebuggerHidden] + public bool TrySetException(Exception exception) + { + if (exception is OperationCanceledException oce) + { + return TrySetCanceled(oce.CancellationToken); + } + + if (UnsafeGetStatus() != UniTaskStatus.Pending) return false; + + this.exception = new ExceptionHolder(ExceptionDispatchInfo.Capture(exception)); + return TrySignalCompletion(UniTaskStatus.Faulted); + } + + [DebuggerHidden] + public void GetResult(short token) + { + MarkHandled(); + + var status = (UniTaskStatus)intStatus; + switch (status) + { + case UniTaskStatus.Succeeded: + return; + case UniTaskStatus.Faulted: + exception.GetException().Throw(); + return; + case UniTaskStatus.Canceled: + throw new OperationCanceledException(cancellationToken); + default: + case UniTaskStatus.Pending: + throw new InvalidOperationException("not yet completed."); + } + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return (UniTaskStatus)intStatus; + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return (UniTaskStatus)intStatus; + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + if (gate == null) + { + Interlocked.CompareExchange(ref gate, new object(), null); + } + + var lockGate = Thread.VolatileRead(ref gate); + lock (lockGate) // wait TrySignalCompletion, after status is not pending. + { + if ((UniTaskStatus)intStatus != UniTaskStatus.Pending) + { + continuation(state); + return; + } + + if (singleContinuation == null) + { + singleContinuation = continuation; + singleState = state; + } + else + { + if (secondaryContinuationList == null) + { + secondaryContinuationList = new List<(Action, object)>(); + } + secondaryContinuationList.Add((continuation, state)); + } + } + } + + [DebuggerHidden] + bool TrySignalCompletion(UniTaskStatus status) + { + if (Interlocked.CompareExchange(ref intStatus, (int)status, (int)UniTaskStatus.Pending) == (int)UniTaskStatus.Pending) + { + if (gate == null) + { + Interlocked.CompareExchange(ref gate, new object(), null); + } + + var lockGate = Thread.VolatileRead(ref gate); + lock (lockGate) // wait OnCompleted. + { + if (singleContinuation != null) + { + try + { + singleContinuation(singleState); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + + if (secondaryContinuationList != null) + { + foreach (var (c, state) in secondaryContinuationList) + { + try + { + c(state); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + } + + singleContinuation = null; + singleState = null; + secondaryContinuationList = null; + } + return true; + } + return false; + } + } + + public class UniTaskCompletionSource : IUniTaskSource, IPromise + { + CancellationToken cancellationToken; + T result; + ExceptionHolder exception; + object gate; + Action singleContinuation; + object singleState; + List<(Action, object)> secondaryContinuationList; + + int intStatus; // UniTaskStatus + bool handled = false; + + public UniTaskCompletionSource() + { + TaskTracker.TrackActiveTask(this, 2); + } + + [DebuggerHidden] + internal void MarkHandled() + { + if (!handled) + { + handled = true; + TaskTracker.RemoveTracking(this); + } + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, 0); + } + } + + [DebuggerHidden] + public bool TrySetResult(T result) + { + if (UnsafeGetStatus() != UniTaskStatus.Pending) return false; + + this.result = result; + return TrySignalCompletion(UniTaskStatus.Succeeded); + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + if (UnsafeGetStatus() != UniTaskStatus.Pending) return false; + + this.cancellationToken = cancellationToken; + return TrySignalCompletion(UniTaskStatus.Canceled); + } + + [DebuggerHidden] + public bool TrySetException(Exception exception) + { + if (exception is OperationCanceledException oce) + { + return TrySetCanceled(oce.CancellationToken); + } + + if (UnsafeGetStatus() != UniTaskStatus.Pending) return false; + + this.exception = new ExceptionHolder(ExceptionDispatchInfo.Capture(exception)); + return TrySignalCompletion(UniTaskStatus.Faulted); + } + + [DebuggerHidden] + public T GetResult(short token) + { + MarkHandled(); + + var status = (UniTaskStatus)intStatus; + switch (status) + { + case UniTaskStatus.Succeeded: + return result; + case UniTaskStatus.Faulted: + exception.GetException().Throw(); + return default; + case UniTaskStatus.Canceled: + throw new OperationCanceledException(cancellationToken); + default: + case UniTaskStatus.Pending: + throw new InvalidOperationException("not yet completed."); + } + } + + [DebuggerHidden] + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return (UniTaskStatus)intStatus; + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return (UniTaskStatus)intStatus; + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + if (gate == null) + { + Interlocked.CompareExchange(ref gate, new object(), null); + } + + var lockGate = Thread.VolatileRead(ref gate); + lock (lockGate) // wait TrySignalCompletion, after status is not pending. + { + if ((UniTaskStatus)intStatus != UniTaskStatus.Pending) + { + continuation(state); + return; + } + + if (singleContinuation == null) + { + singleContinuation = continuation; + singleState = state; + } + else + { + if (secondaryContinuationList == null) + { + secondaryContinuationList = new List<(Action, object)>(); + } + secondaryContinuationList.Add((continuation, state)); + } + } + } + + [DebuggerHidden] + bool TrySignalCompletion(UniTaskStatus status) + { + if (Interlocked.CompareExchange(ref intStatus, (int)status, (int)UniTaskStatus.Pending) == (int)UniTaskStatus.Pending) + { + if (gate == null) + { + Interlocked.CompareExchange(ref gate, new object(), null); + } + + var lockGate = Thread.VolatileRead(ref gate); + lock (lockGate) // wait OnCompleted. + { + if (singleContinuation != null) + { + try + { + singleContinuation(singleState); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + + if (secondaryContinuationList != null) + { + foreach (var (c, state) in secondaryContinuationList) + { + try + { + c(state); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + } + + singleContinuation = null; + singleState = null; + secondaryContinuationList = null; + } + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskCompletionSource.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskCompletionSource.cs.meta new file mode 100644 index 00000000..2ae5ee31 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskCompletionSource.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed03524d09e7eb24a9fb9137198feb84 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.Shorthand.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.Shorthand.cs new file mode 100644 index 00000000..0e51a459 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.Shorthand.cs @@ -0,0 +1,187 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +using System.Collections.Generic; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UniTaskExtensions + { + // shorthand of WhenAll + + public static UniTask.Awaiter GetAwaiter(this UniTask[] tasks) + { + return UniTask.WhenAll(tasks).GetAwaiter(); + } + + public static UniTask.Awaiter GetAwaiter(this IEnumerable tasks) + { + return UniTask.WhenAll(tasks).GetAwaiter(); + } + + public static UniTask.Awaiter GetAwaiter(this UniTask[] tasks) + { + return UniTask.WhenAll(tasks).GetAwaiter(); + } + + public static UniTask.Awaiter GetAwaiter(this IEnumerable> tasks) + { + return UniTask.WhenAll(tasks).GetAwaiter(); + } + + public static UniTask<(T1, T2)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12, tasks.Item13).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12, tasks.Item13, tasks.Item14).GetAwaiter(); + } + + public static UniTask<(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)>.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14, UniTask task15) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12, tasks.Item13, tasks.Item14, tasks.Item15).GetAwaiter(); + } + + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12, tasks.Item13).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12, tasks.Item13, tasks.Item14).GetAwaiter(); + } + + + public static UniTask.Awaiter GetAwaiter(this (UniTask task1, UniTask task2, UniTask task3, UniTask task4, UniTask task5, UniTask task6, UniTask task7, UniTask task8, UniTask task9, UniTask task10, UniTask task11, UniTask task12, UniTask task13, UniTask task14, UniTask task15) tasks) + { + return UniTask.WhenAll(tasks.Item1, tasks.Item2, tasks.Item3, tasks.Item4, tasks.Item5, tasks.Item6, tasks.Item7, tasks.Item8, tasks.Item9, tasks.Item10, tasks.Item11, tasks.Item12, tasks.Item13, tasks.Item14, tasks.Item15).GetAwaiter(); + } + + + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.Shorthand.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.Shorthand.cs.meta new file mode 100644 index 00000000..e2dcc142 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.Shorthand.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b4ff020f73dc6d4b8ebd4760d61fb43 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.cs new file mode 100644 index 00000000..51555679 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.cs @@ -0,0 +1,923 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Collections; +using System.Runtime.ExceptionServices; +using System.Threading; +using System.Threading.Tasks; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UniTaskExtensions + { + /// + /// Convert Task[T] -> UniTask[T]. + /// + public static UniTask AsUniTask(this Task task, bool useCurrentSynchronizationContext = true) + { + var promise = new UniTaskCompletionSource(); + + task.ContinueWith((x, state) => + { + var p = (UniTaskCompletionSource)state; + + switch (x.Status) + { + case TaskStatus.Canceled: + p.TrySetCanceled(); + break; + case TaskStatus.Faulted: + p.TrySetException(x.Exception.InnerException ?? x.Exception); + break; + case TaskStatus.RanToCompletion: + p.TrySetResult(x.Result); + break; + default: + throw new NotSupportedException(); + } + }, promise, useCurrentSynchronizationContext ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current); + + return promise.Task; + } + + /// + /// Convert Task -> UniTask. + /// + public static UniTask AsUniTask(this Task task, bool useCurrentSynchronizationContext = true) + { + var promise = new UniTaskCompletionSource(); + + task.ContinueWith((x, state) => + { + var p = (UniTaskCompletionSource)state; + + switch (x.Status) + { + case TaskStatus.Canceled: + p.TrySetCanceled(); + break; + case TaskStatus.Faulted: + p.TrySetException(x.Exception.InnerException ?? x.Exception); + break; + case TaskStatus.RanToCompletion: + p.TrySetResult(); + break; + default: + throw new NotSupportedException(); + } + }, promise, useCurrentSynchronizationContext ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Current); + + return promise.Task; + } + + public static Task AsTask(this UniTask task) + { + try + { + UniTask.Awaiter awaiter; + try + { + awaiter = task.GetAwaiter(); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + + if (awaiter.IsCompleted) + { + try + { + var result = awaiter.GetResult(); + return Task.FromResult(result); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + + var tcs = new TaskCompletionSource(); + + awaiter.SourceOnCompleted(state => + { + using (var tuple = (StateTuple, UniTask.Awaiter>)state) + { + var (inTcs, inAwaiter) = tuple; + try + { + var result = inAwaiter.GetResult(); + inTcs.SetResult(result); + } + catch (Exception ex) + { + inTcs.SetException(ex); + } + } + }, StateTuple.Create(tcs, awaiter)); + + return tcs.Task; + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + + public static Task AsTask(this UniTask task) + { + try + { + UniTask.Awaiter awaiter; + try + { + awaiter = task.GetAwaiter(); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + + if (awaiter.IsCompleted) + { + try + { + awaiter.GetResult(); // check token valid on Succeeded + return Task.CompletedTask; + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + + var tcs = new TaskCompletionSource(); + + awaiter.SourceOnCompleted(state => + { + using (var tuple = (StateTuple, UniTask.Awaiter>)state) + { + var (inTcs, inAwaiter) = tuple; + try + { + inAwaiter.GetResult(); + inTcs.SetResult(null); + } + catch (Exception ex) + { + inTcs.SetException(ex); + } + } + }, StateTuple.Create(tcs, awaiter)); + + return tcs.Task; + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + + public static AsyncLazy ToAsyncLazy(this UniTask task) + { + return new AsyncLazy(task); + } + + public static AsyncLazy ToAsyncLazy(this UniTask task) + { + return new AsyncLazy(task); + } + + /// + /// Ignore task result when cancel raised first. + /// + public static UniTask AttachExternalCancellation(this UniTask task, CancellationToken cancellationToken) + { + if (!cancellationToken.CanBeCanceled) + { + return task; + } + + if (cancellationToken.IsCancellationRequested) + { + task.Forget(); + return UniTask.FromCanceled(cancellationToken); + } + + if (task.Status.IsCompleted()) + { + return task; + } + + return new UniTask(new AttachExternalCancellationSource(task, cancellationToken), 0); + } + + /// + /// Ignore task result when cancel raised first. + /// + public static UniTask AttachExternalCancellation(this UniTask task, CancellationToken cancellationToken) + { + if (!cancellationToken.CanBeCanceled) + { + return task; + } + + if (cancellationToken.IsCancellationRequested) + { + task.Forget(); + return UniTask.FromCanceled(cancellationToken); + } + + if (task.Status.IsCompleted()) + { + return task; + } + + return new UniTask(new AttachExternalCancellationSource(task, cancellationToken), 0); + } + + sealed class AttachExternalCancellationSource : IUniTaskSource + { + static readonly Action cancellationCallbackDelegate = CancellationCallback; + + CancellationToken cancellationToken; + CancellationTokenRegistration tokenRegistration; + UniTaskCompletionSourceCore core; + + public AttachExternalCancellationSource(UniTask task, CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + this.tokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallbackDelegate, this); + RunTask(task).Forget(); + } + + async UniTaskVoid RunTask(UniTask task) + { + try + { + await task; + core.TrySetResult(AsyncUnit.Default); + } + catch (Exception ex) + { + core.TrySetException(ex); + } + finally + { + tokenRegistration.Dispose(); + } + } + + static void CancellationCallback(object state) + { + var self = (AttachExternalCancellationSource)state; + self.core.TrySetCanceled(self.cancellationToken); + } + + public void GetResult(short token) + { + core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + } + + sealed class AttachExternalCancellationSource : IUniTaskSource + { + static readonly Action cancellationCallbackDelegate = CancellationCallback; + + CancellationToken cancellationToken; + CancellationTokenRegistration tokenRegistration; + UniTaskCompletionSourceCore core; + + public AttachExternalCancellationSource(UniTask task, CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + this.tokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallbackDelegate, this); + RunTask(task).Forget(); + } + + async UniTaskVoid RunTask(UniTask task) + { + try + { + core.TrySetResult(await task); + } + catch (Exception ex) + { + core.TrySetException(ex); + } + finally + { + tokenRegistration.Dispose(); + } + } + + static void CancellationCallback(object state) + { + var self = (AttachExternalCancellationSource)state; + self.core.TrySetCanceled(self.cancellationToken); + } + + void IUniTaskSource.GetResult(short token) + { + core.GetResult(token); + } + + public T GetResult(short token) + { + return core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + } + +#if UNITY_2018_3_OR_NEWER + + public static IEnumerator ToCoroutine(this UniTask task, Action resultHandler = null, Action exceptionHandler = null) + { + return new ToCoroutineEnumerator(task, resultHandler, exceptionHandler); + } + + public static IEnumerator ToCoroutine(this UniTask task, Action exceptionHandler = null) + { + return new ToCoroutineEnumerator(task, exceptionHandler); + } + + public static async UniTask Timeout(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) + { + var delayCancellationTokenSource = new CancellationTokenSource(); + var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); + + int winArgIndex; + bool taskResultIsCanceled; + try + { + (winArgIndex, taskResultIsCanceled, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); + } + catch + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + throw; + } + + // timeout + if (winArgIndex == 1) + { + if (taskCancellationTokenSource != null) + { + taskCancellationTokenSource.Cancel(); + taskCancellationTokenSource.Dispose(); + } + + throw new TimeoutException("Exceed Timeout:" + timeout); + } + else + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + } + + if (taskResultIsCanceled) + { + Error.ThrowOperationCanceledException(); + } + } + + public static async UniTask Timeout(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) + { + var delayCancellationTokenSource = new CancellationTokenSource(); + var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); + + int winArgIndex; + (bool IsCanceled, T Result) taskResult; + try + { + (winArgIndex, taskResult, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); + } + catch + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + throw; + } + + // timeout + if (winArgIndex == 1) + { + if (taskCancellationTokenSource != null) + { + taskCancellationTokenSource.Cancel(); + taskCancellationTokenSource.Dispose(); + } + + throw new TimeoutException("Exceed Timeout:" + timeout); + } + else + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + } + + if (taskResult.IsCanceled) + { + Error.ThrowOperationCanceledException(); + } + + return taskResult.Result; + } + + /// + /// Timeout with suppress OperationCanceledException. Returns (bool, IsCanceled). + /// + public static async UniTask TimeoutWithoutException(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) + { + var delayCancellationTokenSource = new CancellationTokenSource(); + var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); + + int winArgIndex; + bool taskResultIsCanceled; + try + { + (winArgIndex, taskResultIsCanceled, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); + } + catch + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + return true; + } + + // timeout + if (winArgIndex == 1) + { + if (taskCancellationTokenSource != null) + { + taskCancellationTokenSource.Cancel(); + taskCancellationTokenSource.Dispose(); + } + + return true; + } + else + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + } + + if (taskResultIsCanceled) + { + return true; + } + + return false; + } + + /// + /// Timeout with suppress OperationCanceledException. Returns (bool IsTimeout, T Result). + /// + public static async UniTask<(bool IsTimeout, T Result)> TimeoutWithoutException(this UniTask task, TimeSpan timeout, DelayType delayType = DelayType.DeltaTime, PlayerLoopTiming timeoutCheckTiming = PlayerLoopTiming.Update, CancellationTokenSource taskCancellationTokenSource = null) + { + var delayCancellationTokenSource = new CancellationTokenSource(); + var timeoutTask = UniTask.Delay(timeout, delayType, timeoutCheckTiming, delayCancellationTokenSource.Token).SuppressCancellationThrow(); + + int winArgIndex; + (bool IsCanceled, T Result) taskResult; + try + { + (winArgIndex, taskResult, _) = await UniTask.WhenAny(task.SuppressCancellationThrow(), timeoutTask); + } + catch + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + return (true, default); + } + + // timeout + if (winArgIndex == 1) + { + if (taskCancellationTokenSource != null) + { + taskCancellationTokenSource.Cancel(); + taskCancellationTokenSource.Dispose(); + } + + return (true, default); + } + else + { + delayCancellationTokenSource.Cancel(); + delayCancellationTokenSource.Dispose(); + } + + if (taskResult.IsCanceled) + { + return (true, default); + } + + return (false, taskResult.Result); + } + +#endif + + public static void Forget(this UniTask task) + { + var awaiter = task.GetAwaiter(); + if (awaiter.IsCompleted) + { + try + { + awaiter.GetResult(); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple)state) + { + try + { + t.Item1.GetResult(); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + }, StateTuple.Create(awaiter)); + } + } + + public static void Forget(this UniTask task, Action exceptionHandler, bool handleExceptionOnMainThread = true) + { + if (exceptionHandler == null) + { + Forget(task); + } + else + { + ForgetCoreWithCatch(task, exceptionHandler, handleExceptionOnMainThread).Forget(); + } + } + + static async UniTaskVoid ForgetCoreWithCatch(UniTask task, Action exceptionHandler, bool handleExceptionOnMainThread) + { + try + { + await task; + } + catch (Exception ex) + { + try + { + if (handleExceptionOnMainThread) + { +#if UNITY_2018_3_OR_NEWER + await UniTask.SwitchToMainThread(); +#endif + } + exceptionHandler(ex); + } + catch (Exception ex2) + { + UniTaskScheduler.PublishUnobservedTaskException(ex2); + } + } + } + + public static void Forget(this UniTask task) + { + var awaiter = task.GetAwaiter(); + if (awaiter.IsCompleted) + { + try + { + awaiter.GetResult(); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + else + { + awaiter.SourceOnCompleted(state => + { + using (var t = (StateTuple.Awaiter>)state) + { + try + { + t.Item1.GetResult(); + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + } + }, StateTuple.Create(awaiter)); + } + } + + public static void Forget(this UniTask task, Action exceptionHandler, bool handleExceptionOnMainThread = true) + { + if (exceptionHandler == null) + { + task.Forget(); + } + else + { + ForgetCoreWithCatch(task, exceptionHandler, handleExceptionOnMainThread).Forget(); + } + } + + static async UniTaskVoid ForgetCoreWithCatch(UniTask task, Action exceptionHandler, bool handleExceptionOnMainThread) + { + try + { + await task; + } + catch (Exception ex) + { + try + { + if (handleExceptionOnMainThread) + { +#if UNITY_2018_3_OR_NEWER + await UniTask.SwitchToMainThread(); +#endif + } + exceptionHandler(ex); + } + catch (Exception ex2) + { + UniTaskScheduler.PublishUnobservedTaskException(ex2); + } + } + } + + public static async UniTask ContinueWith(this UniTask task, Action continuationFunction) + { + continuationFunction(await task); + } + + public static async UniTask ContinueWith(this UniTask task, Func continuationFunction) + { + await continuationFunction(await task); + } + + public static async UniTask ContinueWith(this UniTask task, Func continuationFunction) + { + return continuationFunction(await task); + } + + public static async UniTask ContinueWith(this UniTask task, Func> continuationFunction) + { + return await continuationFunction(await task); + } + + public static async UniTask ContinueWith(this UniTask task, Action continuationFunction) + { + await task; + continuationFunction(); + } + + public static async UniTask ContinueWith(this UniTask task, Func continuationFunction) + { + await task; + await continuationFunction(); + } + + public static async UniTask ContinueWith(this UniTask task, Func continuationFunction) + { + await task; + return continuationFunction(); + } + + public static async UniTask ContinueWith(this UniTask task, Func> continuationFunction) + { + await task; + return await continuationFunction(); + } + + public static async UniTask Unwrap(this UniTask> task) + { + return await await task; + } + + public static async UniTask Unwrap(this UniTask task) + { + await await task; + } + + public static async UniTask Unwrap(this Task> task) + { + return await await task; + } + + public static async UniTask Unwrap(this Task> task, bool continueOnCapturedContext) + { + return await await task.ConfigureAwait(continueOnCapturedContext); + } + + public static async UniTask Unwrap(this Task task) + { + await await task; + } + + public static async UniTask Unwrap(this Task task, bool continueOnCapturedContext) + { + await await task.ConfigureAwait(continueOnCapturedContext); + } + + public static async UniTask Unwrap(this UniTask> task) + { + return await await task; + } + + public static async UniTask Unwrap(this UniTask> task, bool continueOnCapturedContext) + { + return await (await task).ConfigureAwait(continueOnCapturedContext); + } + + public static async UniTask Unwrap(this UniTask task) + { + await await task; + } + + public static async UniTask Unwrap(this UniTask task, bool continueOnCapturedContext) + { + await (await task).ConfigureAwait(continueOnCapturedContext); + } + +#if UNITY_2018_3_OR_NEWER + + sealed class ToCoroutineEnumerator : IEnumerator + { + bool completed; + UniTask task; + Action exceptionHandler = null; + bool isStarted = false; + ExceptionDispatchInfo exception; + + public ToCoroutineEnumerator(UniTask task, Action exceptionHandler) + { + completed = false; + this.exceptionHandler = exceptionHandler; + this.task = task; + } + + async UniTaskVoid RunTask(UniTask task) + { + try + { + await task; + } + catch (Exception ex) + { + if (exceptionHandler != null) + { + exceptionHandler(ex); + } + else + { + this.exception = ExceptionDispatchInfo.Capture(ex); + } + } + finally + { + completed = true; + } + } + + public object Current => null; + + public bool MoveNext() + { + if (!isStarted) + { + isStarted = true; + RunTask(task).Forget(); + } + + if (exception != null) + { + exception.Throw(); + return false; + } + + return !completed; + } + + void IEnumerator.Reset() + { + } + } + + sealed class ToCoroutineEnumerator : IEnumerator + { + bool completed; + Action resultHandler = null; + Action exceptionHandler = null; + bool isStarted = false; + UniTask task; + object current = null; + ExceptionDispatchInfo exception; + + public ToCoroutineEnumerator(UniTask task, Action resultHandler, Action exceptionHandler) + { + completed = false; + this.task = task; + this.resultHandler = resultHandler; + this.exceptionHandler = exceptionHandler; + } + + async UniTaskVoid RunTask(UniTask task) + { + try + { + var value = await task; + current = value; // boxed if T is struct... + if (resultHandler != null) + { + resultHandler(value); + } + } + catch (Exception ex) + { + if (exceptionHandler != null) + { + exceptionHandler(ex); + } + else + { + this.exception = ExceptionDispatchInfo.Capture(ex); + } + } + finally + { + completed = true; + } + } + + public object Current => current; + + public bool MoveNext() + { + if (!isStarted) + { + isStarted = true; + RunTask(task).Forget(); + } + + if (exception != null) + { + exception.Throw(); + return false; + } + + return !completed; + } + + void IEnumerator.Reset() + { + } + } + +#endif + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.cs.meta new file mode 100644 index 00000000..0d229460 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 05460c617dae1e440861a7438535389f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskObservableExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskObservableExtensions.cs new file mode 100644 index 00000000..d2bd9614 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskObservableExtensions.cs @@ -0,0 +1,750 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.ExceptionServices; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks +{ + public static class UniTaskObservableExtensions + { + public static UniTask ToUniTask(this IObservable source, bool useFirstValue = false, CancellationToken cancellationToken = default) + { + var promise = new UniTaskCompletionSource(); + var disposable = new SingleAssignmentDisposable(); + + var observer = useFirstValue + ? (IObserver)new FirstValueToUniTaskObserver(promise, disposable, cancellationToken) + : (IObserver)new ToUniTaskObserver(promise, disposable, cancellationToken); + + try + { + disposable.Disposable = source.Subscribe(observer); + } + catch (Exception ex) + { + promise.TrySetException(ex); + } + + return promise.Task; + } + + public static IObservable ToObservable(this UniTask task) + { + if (task.Status.IsCompleted()) + { + try + { + return new ReturnObservable(task.GetAwaiter().GetResult()); + } + catch (Exception ex) + { + return new ThrowObservable(ex); + } + } + + var subject = new AsyncSubject(); + Fire(subject, task).Forget(); + return subject; + } + + /// + /// Ideally returns IObservabl[Unit] is best but Cysharp.Threading.Tasks does not have Unit so return AsyncUnit instead. + /// + public static IObservable ToObservable(this UniTask task) + { + if (task.Status.IsCompleted()) + { + try + { + task.GetAwaiter().GetResult(); + return new ReturnObservable(AsyncUnit.Default); + } + catch (Exception ex) + { + return new ThrowObservable(ex); + } + } + + var subject = new AsyncSubject(); + Fire(subject, task).Forget(); + return subject; + } + + static async UniTaskVoid Fire(AsyncSubject subject, UniTask task) + { + T value; + try + { + value = await task; + } + catch (Exception ex) + { + subject.OnError(ex); + return; + } + + subject.OnNext(value); + subject.OnCompleted(); + } + + static async UniTaskVoid Fire(AsyncSubject subject, UniTask task) + { + try + { + await task; + } + catch (Exception ex) + { + subject.OnError(ex); + return; + } + + subject.OnNext(AsyncUnit.Default); + subject.OnCompleted(); + } + + class ToUniTaskObserver : IObserver + { + static readonly Action callback = OnCanceled; + + readonly UniTaskCompletionSource promise; + readonly SingleAssignmentDisposable disposable; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration registration; + + bool hasValue; + T latestValue; + + public ToUniTaskObserver(UniTaskCompletionSource promise, SingleAssignmentDisposable disposable, CancellationToken cancellationToken) + { + this.promise = promise; + this.disposable = disposable; + this.cancellationToken = cancellationToken; + + if (this.cancellationToken.CanBeCanceled) + { + this.registration = this.cancellationToken.RegisterWithoutCaptureExecutionContext(callback, this); + } + } + + static void OnCanceled(object state) + { + var self = (ToUniTaskObserver)state; + self.disposable.Dispose(); + self.promise.TrySetCanceled(self.cancellationToken); + } + + public void OnNext(T value) + { + hasValue = true; + latestValue = value; + } + + public void OnError(Exception error) + { + try + { + promise.TrySetException(error); + } + finally + { + registration.Dispose(); + disposable.Dispose(); + } + } + + public void OnCompleted() + { + try + { + if (hasValue) + { + promise.TrySetResult(latestValue); + } + else + { + promise.TrySetException(new InvalidOperationException("Sequence has no elements")); + } + } + finally + { + registration.Dispose(); + disposable.Dispose(); + } + } + } + + class FirstValueToUniTaskObserver : IObserver + { + static readonly Action callback = OnCanceled; + + readonly UniTaskCompletionSource promise; + readonly SingleAssignmentDisposable disposable; + readonly CancellationToken cancellationToken; + readonly CancellationTokenRegistration registration; + + bool hasValue; + + public FirstValueToUniTaskObserver(UniTaskCompletionSource promise, SingleAssignmentDisposable disposable, CancellationToken cancellationToken) + { + this.promise = promise; + this.disposable = disposable; + this.cancellationToken = cancellationToken; + + if (this.cancellationToken.CanBeCanceled) + { + this.registration = this.cancellationToken.RegisterWithoutCaptureExecutionContext(callback, this); + } + } + + static void OnCanceled(object state) + { + var self = (FirstValueToUniTaskObserver)state; + self.disposable.Dispose(); + self.promise.TrySetCanceled(self.cancellationToken); + } + + public void OnNext(T value) + { + hasValue = true; + try + { + promise.TrySetResult(value); + } + finally + { + registration.Dispose(); + disposable.Dispose(); + } + } + + public void OnError(Exception error) + { + try + { + promise.TrySetException(error); + } + finally + { + registration.Dispose(); + disposable.Dispose(); + } + } + + public void OnCompleted() + { + try + { + if (!hasValue) + { + promise.TrySetException(new InvalidOperationException("Sequence has no elements")); + } + } + finally + { + registration.Dispose(); + disposable.Dispose(); + } + } + } + + class ReturnObservable : IObservable + { + readonly T value; + + public ReturnObservable(T value) + { + this.value = value; + } + + public IDisposable Subscribe(IObserver observer) + { + observer.OnNext(value); + observer.OnCompleted(); + return EmptyDisposable.Instance; + } + } + + class ThrowObservable : IObservable + { + readonly Exception value; + + public ThrowObservable(Exception value) + { + this.value = value; + } + + public IDisposable Subscribe(IObserver observer) + { + observer.OnError(value); + return EmptyDisposable.Instance; + } + } + } +} + +namespace Cysharp.Threading.Tasks.Internal +{ + // Bridges for Rx. + + internal class EmptyDisposable : IDisposable + { + public static EmptyDisposable Instance = new EmptyDisposable(); + + EmptyDisposable() + { + + } + + public void Dispose() + { + } + } + + internal sealed class SingleAssignmentDisposable : IDisposable + { + readonly object gate = new object(); + IDisposable current; + bool disposed; + + public bool IsDisposed { get { lock (gate) { return disposed; } } } + + public IDisposable Disposable + { + get + { + return current; + } + set + { + var old = default(IDisposable); + bool alreadyDisposed; + lock (gate) + { + alreadyDisposed = disposed; + old = current; + if (!alreadyDisposed) + { + if (value == null) return; + current = value; + } + } + + if (alreadyDisposed && value != null) + { + value.Dispose(); + return; + } + + if (old != null) throw new InvalidOperationException("Disposable is already set"); + } + } + + + public void Dispose() + { + IDisposable old = null; + + lock (gate) + { + if (!disposed) + { + disposed = true; + old = current; + current = null; + } + } + + if (old != null) old.Dispose(); + } + } + + internal sealed class AsyncSubject : IObservable, IObserver + { + object observerLock = new object(); + + T lastValue; + bool hasValue; + bool isStopped; + bool isDisposed; + Exception lastError; + IObserver outObserver = EmptyObserver.Instance; + + public T Value + { + get + { + ThrowIfDisposed(); + if (!isStopped) throw new InvalidOperationException("AsyncSubject is not completed yet"); + if (lastError != null) ExceptionDispatchInfo.Capture(lastError).Throw(); + return lastValue; + } + } + + public bool HasObservers + { + get + { + return !(outObserver is EmptyObserver) && !isStopped && !isDisposed; + } + } + + public bool IsCompleted { get { return isStopped; } } + + public void OnCompleted() + { + IObserver old; + T v; + bool hv; + lock (observerLock) + { + ThrowIfDisposed(); + if (isStopped) return; + + old = outObserver; + outObserver = EmptyObserver.Instance; + isStopped = true; + v = lastValue; + hv = hasValue; + } + + if (hv) + { + old.OnNext(v); + old.OnCompleted(); + } + else + { + old.OnCompleted(); + } + } + + public void OnError(Exception error) + { + if (error == null) throw new ArgumentNullException("error"); + + IObserver old; + lock (observerLock) + { + ThrowIfDisposed(); + if (isStopped) return; + + old = outObserver; + outObserver = EmptyObserver.Instance; + isStopped = true; + lastError = error; + } + + old.OnError(error); + } + + public void OnNext(T value) + { + lock (observerLock) + { + ThrowIfDisposed(); + if (isStopped) return; + + this.hasValue = true; + this.lastValue = value; + } + } + + public IDisposable Subscribe(IObserver observer) + { + if (observer == null) throw new ArgumentNullException("observer"); + + var ex = default(Exception); + var v = default(T); + var hv = false; + + lock (observerLock) + { + ThrowIfDisposed(); + if (!isStopped) + { + var listObserver = outObserver as ListObserver; + if (listObserver != null) + { + outObserver = listObserver.Add(observer); + } + else + { + var current = outObserver; + if (current is EmptyObserver) + { + outObserver = observer; + } + else + { + outObserver = new ListObserver(new ImmutableList>(new[] { current, observer })); + } + } + + return new Subscription(this, observer); + } + + ex = lastError; + v = lastValue; + hv = hasValue; + } + + if (ex != null) + { + observer.OnError(ex); + } + else if (hv) + { + observer.OnNext(v); + observer.OnCompleted(); + } + else + { + observer.OnCompleted(); + } + + return EmptyDisposable.Instance; + } + + public void Dispose() + { + lock (observerLock) + { + isDisposed = true; + outObserver = DisposedObserver.Instance; + lastError = null; + lastValue = default(T); + } + } + + void ThrowIfDisposed() + { + if (isDisposed) throw new ObjectDisposedException(""); + } + + class Subscription : IDisposable + { + readonly object gate = new object(); + AsyncSubject parent; + IObserver unsubscribeTarget; + + public Subscription(AsyncSubject parent, IObserver unsubscribeTarget) + { + this.parent = parent; + this.unsubscribeTarget = unsubscribeTarget; + } + + public void Dispose() + { + lock (gate) + { + if (parent != null) + { + lock (parent.observerLock) + { + var listObserver = parent.outObserver as ListObserver; + if (listObserver != null) + { + parent.outObserver = listObserver.Remove(unsubscribeTarget); + } + else + { + parent.outObserver = EmptyObserver.Instance; + } + + unsubscribeTarget = null; + parent = null; + } + } + } + } + } + } + + internal class ListObserver : IObserver + { + private readonly ImmutableList> _observers; + + public ListObserver(ImmutableList> observers) + { + _observers = observers; + } + + public void OnCompleted() + { + var targetObservers = _observers.Data; + for (int i = 0; i < targetObservers.Length; i++) + { + targetObservers[i].OnCompleted(); + } + } + + public void OnError(Exception error) + { + var targetObservers = _observers.Data; + for (int i = 0; i < targetObservers.Length; i++) + { + targetObservers[i].OnError(error); + } + } + + public void OnNext(T value) + { + var targetObservers = _observers.Data; + for (int i = 0; i < targetObservers.Length; i++) + { + targetObservers[i].OnNext(value); + } + } + + internal IObserver Add(IObserver observer) + { + return new ListObserver(_observers.Add(observer)); + } + + internal IObserver Remove(IObserver observer) + { + var i = Array.IndexOf(_observers.Data, observer); + if (i < 0) + return this; + + if (_observers.Data.Length == 2) + { + return _observers.Data[1 - i]; + } + else + { + return new ListObserver(_observers.Remove(observer)); + } + } + } + + internal class EmptyObserver : IObserver + { + public static readonly EmptyObserver Instance = new EmptyObserver(); + + EmptyObserver() + { + + } + + public void OnCompleted() + { + } + + public void OnError(Exception error) + { + } + + public void OnNext(T value) + { + } + } + + internal class ThrowObserver : IObserver + { + public static readonly ThrowObserver Instance = new ThrowObserver(); + + ThrowObserver() + { + + } + + public void OnCompleted() + { + } + + public void OnError(Exception error) + { + ExceptionDispatchInfo.Capture(error).Throw(); + } + + public void OnNext(T value) + { + } + } + + internal class DisposedObserver : IObserver + { + public static readonly DisposedObserver Instance = new DisposedObserver(); + + DisposedObserver() + { + + } + + public void OnCompleted() + { + throw new ObjectDisposedException(""); + } + + public void OnError(Exception error) + { + throw new ObjectDisposedException(""); + } + + public void OnNext(T value) + { + throw new ObjectDisposedException(""); + } + } + + internal class ImmutableList + { + public static readonly ImmutableList Empty = new ImmutableList(); + + T[] data; + + public T[] Data + { + get { return data; } + } + + ImmutableList() + { + data = new T[0]; + } + + public ImmutableList(T[] data) + { + this.data = data; + } + + public ImmutableList Add(T value) + { + var newData = new T[data.Length + 1]; + Array.Copy(data, newData, data.Length); + newData[data.Length] = value; + return new ImmutableList(newData); + } + + public ImmutableList Remove(T value) + { + var i = IndexOf(value); + if (i < 0) return this; + + var length = data.Length; + if (length == 1) return Empty; + + var newData = new T[length - 1]; + + Array.Copy(data, 0, newData, 0, i); + Array.Copy(data, i + 1, newData, i, length - i - 1); + + return new ImmutableList(newData); + } + + public int IndexOf(T value) + { + for (var i = 0; i < data.Length; ++i) + { + // ImmutableList only use for IObserver(no worry for boxed) + if (object.Equals(data[i], value)) return i; + } + return -1; + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskObservableExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskObservableExtensions.cs.meta new file mode 100644 index 00000000..527a49fc --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskObservableExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eaea262a5ad393d419c15b3b2901d664 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskScheduler.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskScheduler.cs new file mode 100644 index 00000000..2f91f2ad --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskScheduler.cs @@ -0,0 +1,103 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + // UniTask has no scheduler like TaskScheduler. + // Only handle unobserved exception. + + public static class UniTaskScheduler + { + public static event Action UnobservedTaskException; + + /// + /// Propagate OperationCanceledException to UnobservedTaskException when true. Default is false. + /// + public static bool PropagateOperationCanceledException = false; + +#if UNITY_2018_3_OR_NEWER + + /// + /// Write log type when catch unobserved exception and not registered UnobservedTaskException. Default is Exception. + /// + public static UnityEngine.LogType UnobservedExceptionWriteLogType = UnityEngine.LogType.Exception; + + /// + /// Dispatch exception event to Unity MainThread. Default is true. + /// + public static bool DispatchUnityMainThread = true; + + // cache delegate. + static readonly SendOrPostCallback handleExceptionInvoke = InvokeUnobservedTaskException; + + static void InvokeUnobservedTaskException(object state) + { + UnobservedTaskException((Exception)state); + } +#endif + + internal static void PublishUnobservedTaskException(Exception ex) + { + if (ex != null) + { + if (!PropagateOperationCanceledException && ex is OperationCanceledException) + { + return; + } + + if (UnobservedTaskException != null) + { +#if UNITY_2018_3_OR_NEWER + if (!DispatchUnityMainThread || Thread.CurrentThread.ManagedThreadId == PlayerLoopHelper.MainThreadId) + { + // allows inlining call. + UnobservedTaskException.Invoke(ex); + } + else + { + // Post to MainThread. + PlayerLoopHelper.UnitySynchronizationContext.Post(handleExceptionInvoke, ex); + } +#else + UnobservedTaskException.Invoke(ex); +#endif + } + else + { +#if UNITY_2018_3_OR_NEWER + string msg = null; + if (UnobservedExceptionWriteLogType != UnityEngine.LogType.Exception) + { + msg = "UnobservedTaskException: " + ex.ToString(); + } + switch (UnobservedExceptionWriteLogType) + { + case UnityEngine.LogType.Error: + UnityEngine.Debug.LogError(msg); + break; + case UnityEngine.LogType.Assert: + UnityEngine.Debug.LogAssertion(msg); + break; + case UnityEngine.LogType.Warning: + UnityEngine.Debug.LogWarning(msg); + break; + case UnityEngine.LogType.Log: + UnityEngine.Debug.Log(msg); + break; + case UnityEngine.LogType.Exception: + UnityEngine.Debug.LogException(ex); + break; + default: + break; + } +#else + Console.WriteLine("UnobservedTaskException: " + ex.ToString()); +#endif + } + } + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskScheduler.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskScheduler.cs.meta new file mode 100644 index 00000000..5e29191f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6cad69921702d5488d96b5ef30df1b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskSynchronizationContext.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskSynchronizationContext.cs new file mode 100644 index 00000000..450e019f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskSynchronizationContext.cs @@ -0,0 +1,158 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public class UniTaskSynchronizationContext : SynchronizationContext + { + const int MaxArrayLength = 0X7FEFFFFF; + const int InitialSize = 16; + + static SpinLock gate = new SpinLock(false); + static bool dequing = false; + + static int actionListCount = 0; + static Callback[] actionList = new Callback[InitialSize]; + + static int waitingListCount = 0; + static Callback[] waitingList = new Callback[InitialSize]; + + static int opCount; + + public override void Send(SendOrPostCallback d, object state) + { + d(state); + } + + public override void Post(SendOrPostCallback d, object state) + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + + if (dequing) + { + // Ensure Capacity + if (waitingList.Length == waitingListCount) + { + var newLength = waitingListCount * 2; + if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength; + + var newArray = new Callback[newLength]; + Array.Copy(waitingList, newArray, waitingListCount); + waitingList = newArray; + } + waitingList[waitingListCount] = new Callback(d, state); + waitingListCount++; + } + else + { + // Ensure Capacity + if (actionList.Length == actionListCount) + { + var newLength = actionListCount * 2; + if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength; + + var newArray = new Callback[newLength]; + Array.Copy(actionList, newArray, actionListCount); + actionList = newArray; + } + actionList[actionListCount] = new Callback(d, state); + actionListCount++; + } + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + public override void OperationStarted() + { + Interlocked.Increment(ref opCount); + } + + public override void OperationCompleted() + { + Interlocked.Decrement(ref opCount); + } + + public override SynchronizationContext CreateCopy() + { + return this; + } + + // delegate entrypoint. + internal static void Run() + { + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + if (actionListCount == 0) return; + dequing = true; + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + + for (int i = 0; i < actionListCount; i++) + { + var action = actionList[i]; + actionList[i] = default; + action.Invoke(); + } + + { + bool lockTaken = false; + try + { + gate.Enter(ref lockTaken); + dequing = false; + + var swapTempActionList = actionList; + + actionListCount = waitingListCount; + actionList = waitingList; + + waitingListCount = 0; + waitingList = swapTempActionList; + } + finally + { + if (lockTaken) gate.Exit(false); + } + } + } + + [StructLayout(LayoutKind.Auto)] + readonly struct Callback + { + readonly SendOrPostCallback callback; + readonly object state; + + public Callback(SendOrPostCallback callback, object state) + { + this.callback = callback; + this.state = state; + } + + public void Invoke() + { + try + { + callback(state); + } + catch (Exception ex) + { + UnityEngine.Debug.LogException(ex); + } + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskSynchronizationContext.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskSynchronizationContext.cs.meta new file mode 100644 index 00000000..9828c893 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskSynchronizationContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: abf3aae9813db2849bce518f8596e920 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskVoid.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskVoid.cs new file mode 100644 index 00000000..c7e9ed98 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskVoid.cs @@ -0,0 +1,19 @@ +#pragma warning disable CS1591 +#pragma warning disable CS0436 + +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Cysharp.Threading.Tasks.CompilerServices; + +namespace Cysharp.Threading.Tasks +{ + [AsyncMethodBuilder(typeof(AsyncUniTaskVoidMethodBuilder))] + public readonly struct UniTaskVoid + { + public void Forget() + { + } + } +} + diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskVoid.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskVoid.cs.meta new file mode 100644 index 00000000..01f7156c --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UniTaskVoid.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e9f28cd922179634d863011548f89ae7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AssetBundleRequestAllAssets.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AssetBundleRequestAllAssets.cs new file mode 100644 index 00000000..b246ffd1 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AssetBundleRequestAllAssets.cs @@ -0,0 +1,254 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +#if UNITY_2018_4 || UNITY_2019_4_OR_NEWER +#if UNITASK_ASSETBUNDLE_SUPPORT + +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UnityAsyncExtensions + { + public static AssetBundleRequestAllAssetsAwaiter AwaitForAllAssets(this AssetBundleRequest asyncOperation) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + return new AssetBundleRequestAllAssetsAwaiter(asyncOperation); + } + + public static UniTask AwaitForAllAssets(this AssetBundleRequest asyncOperation, CancellationToken cancellationToken) + { + return AwaitForAllAssets(asyncOperation, null, PlayerLoopTiming.Update, cancellationToken: cancellationToken); + } + + public static UniTask AwaitForAllAssets(this AssetBundleRequest asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return AwaitForAllAssets(asyncOperation, progress: null, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask AwaitForAllAssets(this AssetBundleRequest asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.FromResult(asyncOperation.allAssets); + return new UniTask(AssetBundleRequestAllAssetsConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public struct AssetBundleRequestAllAssetsAwaiter : ICriticalNotifyCompletion + { + AssetBundleRequest asyncOperation; + Action continuationAction; + + public AssetBundleRequestAllAssetsAwaiter(AssetBundleRequest asyncOperation) + { + this.asyncOperation = asyncOperation; + this.continuationAction = null; + } + + public AssetBundleRequestAllAssetsAwaiter GetAwaiter() + { + return this; + } + + public bool IsCompleted => asyncOperation.isDone; + + public UnityEngine.Object[] GetResult() + { + if (continuationAction != null) + { + asyncOperation.completed -= continuationAction; + continuationAction = null; + var result = asyncOperation.allAssets; + asyncOperation = null; + return result; + } + else + { + var result = asyncOperation.allAssets; + asyncOperation = null; + return result; + } + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + asyncOperation.completed += continuationAction; + } + } + + sealed class AssetBundleRequestAllAssetsConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AssetBundleRequestAllAssetsConfiguredSource nextNode; + public ref AssetBundleRequestAllAssetsConfiguredSource NextNode => ref nextNode; + + static AssetBundleRequestAllAssetsConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AssetBundleRequestAllAssetsConfiguredSource), () => pool.Size); + } + + AssetBundleRequest asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + AssetBundleRequestAllAssetsConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(AssetBundleRequest asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AssetBundleRequestAllAssetsConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (AssetBundleRequestAllAssetsConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public UnityEngine.Object[] GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(asyncOperation.allAssets); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(asyncOperation.allAssets); + } + } + } + } +} + +#endif +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AssetBundleRequestAllAssets.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AssetBundleRequestAllAssets.cs.meta new file mode 100644 index 00000000..79be9231 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AssetBundleRequestAllAssets.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e9147caba40da434da95b39709c13784 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncGPUReadback.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncGPUReadback.cs new file mode 100644 index 00000000..cd9fa8e5 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncGPUReadback.cs @@ -0,0 +1,164 @@ + #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; +using UnityEngine.Rendering; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UnityAsyncExtensions + { + #region AsyncGPUReadbackRequest + + public static UniTask.Awaiter GetAwaiter(this AsyncGPUReadbackRequest asyncOperation) + { + return ToUniTask(asyncOperation).GetAwaiter(); + } + + public static UniTask WithCancellation(this AsyncGPUReadbackRequest asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this AsyncGPUReadbackRequest asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this AsyncGPUReadbackRequest asyncOperation, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + if (asyncOperation.done) return UniTask.FromResult(asyncOperation); + return new UniTask(AsyncGPUReadbackRequestAwaiterConfiguredSource.Create(asyncOperation, timing, cancellationToken, cancelImmediately, out var token), token); + } + + sealed class AsyncGPUReadbackRequestAwaiterConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AsyncGPUReadbackRequestAwaiterConfiguredSource nextNode; + public ref AsyncGPUReadbackRequestAwaiterConfiguredSource NextNode => ref nextNode; + + static AsyncGPUReadbackRequestAwaiterConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AsyncGPUReadbackRequestAwaiterConfiguredSource), () => pool.Size); + } + + AsyncGPUReadbackRequest asyncOperation; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + UniTaskCompletionSourceCore core; + + AsyncGPUReadbackRequestAwaiterConfiguredSource() + { + } + + public static IUniTaskSource Create(AsyncGPUReadbackRequest asyncOperation, PlayerLoopTiming timing, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AsyncGPUReadbackRequestAwaiterConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var promise = (AsyncGPUReadbackRequestAwaiterConfiguredSource)state; + promise.core.TrySetCanceled(promise.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public AsyncGPUReadbackRequest GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (asyncOperation.hasError) + { + core.TrySetException(new Exception("AsyncGPUReadbackRequest.hasError = true")); + return false; + } + + if (asyncOperation.done) + { + core.TrySetResult(asyncOperation); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncGPUReadback.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncGPUReadback.cs.meta new file mode 100644 index 00000000..510c49e3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncGPUReadback.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 98f5fedb44749ab4688674d79126b46a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncInstantiate.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncInstantiate.cs new file mode 100644 index 00000000..c36b5d1d --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncInstantiate.cs @@ -0,0 +1,386 @@ +// AsyncInstantiateOperation was added since Unity 2022.3.20 / 2023.3.0b7 +#if UNITY_2022_3 && !(UNITY_2022_3_0 || UNITY_2022_3_1 || UNITY_2022_3_2 || UNITY_2022_3_3 || UNITY_2022_3_4 || UNITY_2022_3_5 || UNITY_2022_3_6 || UNITY_2022_3_7 || UNITY_2022_3_8 || UNITY_2022_3_9 || UNITY_2022_3_10 || UNITY_2022_3_11 || UNITY_2022_3_12 || UNITY_2022_3_13 || UNITY_2022_3_14 || UNITY_2022_3_15 || UNITY_2022_3_16 || UNITY_2022_3_17 || UNITY_2022_3_18 || UNITY_2022_3_19) +#define UNITY_2022_SUPPORT +#endif + +#if UNITY_2022_SUPPORT || UNITY_2023_3_OR_NEWER + +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; +using UnityEngine; + +namespace Cysharp.Threading.Tasks +{ + public static class AsyncInstantiateOperationExtensions + { + // AsyncInstantiateOperation has GetAwaiter so no need to impl + // public static UniTask.Awaiter GetAwaiter(this AsyncInstantiateOperation operation) where T : Object + + public static UniTask WithCancellation(this AsyncInstantiateOperation asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this AsyncInstantiateOperation asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this AsyncInstantiateOperation asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.FromResult(asyncOperation.Result); + return new UniTask(AsyncInstantiateOperationConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public static UniTask WithCancellation(this AsyncInstantiateOperation asyncOperation, CancellationToken cancellationToken) + where T : UnityEngine.Object + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this AsyncInstantiateOperation asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + where T : UnityEngine.Object + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this AsyncInstantiateOperation asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + where T : UnityEngine.Object + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.FromResult(asyncOperation.Result); + return new UniTask(AsyncInstantiateOperationConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + sealed class AsyncInstantiateOperationConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AsyncInstantiateOperationConfiguredSource nextNode; + public ref AsyncInstantiateOperationConfiguredSource NextNode => ref nextNode; + + static AsyncInstantiateOperationConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AsyncInstantiateOperationConfiguredSource), () => pool.Size); + } + + AsyncInstantiateOperation asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + AsyncInstantiateOperationConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(AsyncInstantiateOperation asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AsyncInstantiateOperationConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (AsyncInstantiateOperationConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public UnityEngine.Object[] GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(asyncOperation.Result); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(asyncOperation.Result); + } + } + } + + sealed class AsyncInstantiateOperationConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode> + where T : UnityEngine.Object + { + static TaskPool> pool; + AsyncInstantiateOperationConfiguredSource nextNode; + public ref AsyncInstantiateOperationConfiguredSource NextNode => ref nextNode; + + static AsyncInstantiateOperationConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AsyncInstantiateOperationConfiguredSource), () => pool.Size); + } + + AsyncInstantiateOperation asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + AsyncInstantiateOperationConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(AsyncInstantiateOperation asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AsyncInstantiateOperationConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (AsyncInstantiateOperationConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public T[] GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(asyncOperation.Result); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(asyncOperation.Result); + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncInstantiate.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncInstantiate.cs.meta new file mode 100644 index 00000000..85f9768b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.AsyncInstantiate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8321f4244edfdcd4798b4fcc92a736c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.Jobs.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.Jobs.cs new file mode 100644 index 00000000..db0a8922 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.Jobs.cs @@ -0,0 +1,102 @@ +#if ENABLE_MANAGED_JOBS +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Threading; +using Unity.Jobs; +using UnityEngine; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UnityAsyncExtensions + { + public static async UniTask WaitAsync(this JobHandle jobHandle, PlayerLoopTiming waitTiming, CancellationToken cancellationToken = default) + { + await UniTask.Yield(waitTiming); + jobHandle.Complete(); + cancellationToken.ThrowIfCancellationRequested(); // call cancel after Complete. + } + + public static UniTask.Awaiter GetAwaiter(this JobHandle jobHandle) + { + var handler = JobHandlePromise.Create(jobHandle, out var token); + { + PlayerLoopHelper.AddAction(PlayerLoopTiming.EarlyUpdate, handler); + PlayerLoopHelper.AddAction(PlayerLoopTiming.PreUpdate, handler); + PlayerLoopHelper.AddAction(PlayerLoopTiming.Update, handler); + PlayerLoopHelper.AddAction(PlayerLoopTiming.PreLateUpdate, handler); + PlayerLoopHelper.AddAction(PlayerLoopTiming.PostLateUpdate, handler); + } + + return new UniTask(handler, token).GetAwaiter(); + } + + // can not pass CancellationToken because can't handle JobHandle's Complete and NativeArray.Dispose. + + public static UniTask ToUniTask(this JobHandle jobHandle, PlayerLoopTiming waitTiming) + { + var handler = JobHandlePromise.Create(jobHandle, out var token); + { + PlayerLoopHelper.AddAction(waitTiming, handler); + } + + return new UniTask(handler, token); + } + + sealed class JobHandlePromise : IUniTaskSource, IPlayerLoopItem + { + JobHandle jobHandle; + + UniTaskCompletionSourceCore core; + + // Cancellation is not supported. + public static JobHandlePromise Create(JobHandle jobHandle, out short token) + { + // not use pool. + var result = new JobHandlePromise(); + + result.jobHandle = jobHandle; + + TaskTracker.TrackActiveTask(result, 3); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + TaskTracker.RemoveTracking(this); + core.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + if (jobHandle.IsCompleted | PlayerLoopHelper.IsEditorApplicationQuitting) + { + jobHandle.Complete(); + core.TrySetResult(AsyncUnit.Default); + return false; + } + + return true; + } + } + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.Jobs.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.Jobs.cs.meta new file mode 100644 index 00000000..c07df0b8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.Jobs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 30979a768fbd4b94f8694eee8a305c99 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.MonoBehaviour.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.MonoBehaviour.cs new file mode 100644 index 00000000..fdfe55ca --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.MonoBehaviour.cs @@ -0,0 +1,14 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UnityAsyncExtensions + { + public static UniTask StartAsyncCoroutine(this UnityEngine.MonoBehaviour monoBehaviour, Func asyncCoroutine) + { + var token = monoBehaviour.GetCancellationTokenOnDestroy(); + return asyncCoroutine(token); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.MonoBehaviour.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.MonoBehaviour.cs.meta new file mode 100644 index 00000000..6e45863f --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.MonoBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2edd588bb09eb0a4695d039d6a1f02b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs new file mode 100644 index 00000000..1fb5f429 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs @@ -0,0 +1,1216 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using UnityEngine; +using Cysharp.Threading.Tasks.Internal; +#if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT) +using UnityEngine.Networking; +#endif + +namespace Cysharp.Threading.Tasks +{ + public static partial class UnityAsyncExtensions + { + #region AsyncOperation + +#if !UNITY_2023_1_OR_NEWER + // from Unity2023.1.0a15, AsyncOperationAwaitableExtensions.GetAwaiter is defined in UnityEngine. + public static AsyncOperationAwaiter GetAwaiter(this AsyncOperation asyncOperation) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + return new AsyncOperationAwaiter(asyncOperation); + } +#endif + + public static UniTask WithCancellation(this AsyncOperation asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this AsyncOperation asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this AsyncOperation asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.CompletedTask; + return new UniTask(AsyncOperationConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public struct AsyncOperationAwaiter : ICriticalNotifyCompletion + { + AsyncOperation asyncOperation; + Action continuationAction; + + public AsyncOperationAwaiter(AsyncOperation asyncOperation) + { + this.asyncOperation = asyncOperation; + this.continuationAction = null; + } + + public bool IsCompleted => asyncOperation.isDone; + + public void GetResult() + { + if (continuationAction != null) + { + asyncOperation.completed -= continuationAction; + continuationAction = null; + asyncOperation = null; + } + else + { + asyncOperation = null; + } + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + asyncOperation.completed += continuationAction; + } + } + + sealed class AsyncOperationConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AsyncOperationConfiguredSource nextNode; + public ref AsyncOperationConfiguredSource NextNode => ref nextNode; + + static AsyncOperationConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AsyncOperationConfiguredSource), () => pool.Size); + } + + AsyncOperation asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + AsyncOperationConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(AsyncOperation asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AsyncOperationConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (AsyncOperationConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(AsyncUnit.Default); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(AsyncUnit.Default); + } + } + } + + #endregion + + #region ResourceRequest + + public static ResourceRequestAwaiter GetAwaiter(this ResourceRequest asyncOperation) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + return new ResourceRequestAwaiter(asyncOperation); + } + + public static UniTask WithCancellation(this ResourceRequest asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this ResourceRequest asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this ResourceRequest asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.FromResult(asyncOperation.asset); + return new UniTask(ResourceRequestConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public struct ResourceRequestAwaiter : ICriticalNotifyCompletion + { + ResourceRequest asyncOperation; + Action continuationAction; + + public ResourceRequestAwaiter(ResourceRequest asyncOperation) + { + this.asyncOperation = asyncOperation; + this.continuationAction = null; + } + + public bool IsCompleted => asyncOperation.isDone; + + public UnityEngine.Object GetResult() + { + if (continuationAction != null) + { + asyncOperation.completed -= continuationAction; + continuationAction = null; + var result = asyncOperation.asset; + asyncOperation = null; + return result; + } + else + { + var result = asyncOperation.asset; + asyncOperation = null; + return result; + } + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + asyncOperation.completed += continuationAction; + } + } + + sealed class ResourceRequestConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + ResourceRequestConfiguredSource nextNode; + public ref ResourceRequestConfiguredSource NextNode => ref nextNode; + + static ResourceRequestConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(ResourceRequestConfiguredSource), () => pool.Size); + } + + ResourceRequest asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + ResourceRequestConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(ResourceRequest asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new ResourceRequestConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (ResourceRequestConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public UnityEngine.Object GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(asyncOperation.asset); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(asyncOperation.asset); + } + } + } + + #endregion + +#if UNITASK_ASSETBUNDLE_SUPPORT + #region AssetBundleRequest + + public static AssetBundleRequestAwaiter GetAwaiter(this AssetBundleRequest asyncOperation) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + return new AssetBundleRequestAwaiter(asyncOperation); + } + + public static UniTask WithCancellation(this AssetBundleRequest asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this AssetBundleRequest asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this AssetBundleRequest asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.FromResult(asyncOperation.asset); + return new UniTask(AssetBundleRequestConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public struct AssetBundleRequestAwaiter : ICriticalNotifyCompletion + { + AssetBundleRequest asyncOperation; + Action continuationAction; + + public AssetBundleRequestAwaiter(AssetBundleRequest asyncOperation) + { + this.asyncOperation = asyncOperation; + this.continuationAction = null; + } + + public bool IsCompleted => asyncOperation.isDone; + + public UnityEngine.Object GetResult() + { + if (continuationAction != null) + { + asyncOperation.completed -= continuationAction; + continuationAction = null; + var result = asyncOperation.asset; + asyncOperation = null; + return result; + } + else + { + var result = asyncOperation.asset; + asyncOperation = null; + return result; + } + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + asyncOperation.completed += continuationAction; + } + } + + sealed class AssetBundleRequestConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AssetBundleRequestConfiguredSource nextNode; + public ref AssetBundleRequestConfiguredSource NextNode => ref nextNode; + + static AssetBundleRequestConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AssetBundleRequestConfiguredSource), () => pool.Size); + } + + AssetBundleRequest asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + AssetBundleRequestConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(AssetBundleRequest asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AssetBundleRequestConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (AssetBundleRequestConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public UnityEngine.Object GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(asyncOperation.asset); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(asyncOperation.asset); + } + } + } + + #endregion +#endif + +#if UNITASK_ASSETBUNDLE_SUPPORT + #region AssetBundleCreateRequest + + public static AssetBundleCreateRequestAwaiter GetAwaiter(this AssetBundleCreateRequest asyncOperation) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + return new AssetBundleCreateRequestAwaiter(asyncOperation); + } + + public static UniTask WithCancellation(this AssetBundleCreateRequest asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this AssetBundleCreateRequest asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this AssetBundleCreateRequest asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) return UniTask.FromResult(asyncOperation.assetBundle); + return new UniTask(AssetBundleCreateRequestConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public struct AssetBundleCreateRequestAwaiter : ICriticalNotifyCompletion + { + AssetBundleCreateRequest asyncOperation; + Action continuationAction; + + public AssetBundleCreateRequestAwaiter(AssetBundleCreateRequest asyncOperation) + { + this.asyncOperation = asyncOperation; + this.continuationAction = null; + } + + public bool IsCompleted => asyncOperation.isDone; + + public AssetBundle GetResult() + { + if (continuationAction != null) + { + asyncOperation.completed -= continuationAction; + continuationAction = null; + var result = asyncOperation.assetBundle; + asyncOperation = null; + return result; + } + else + { + var result = asyncOperation.assetBundle; + asyncOperation = null; + return result; + } + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + asyncOperation.completed += continuationAction; + } + } + + sealed class AssetBundleCreateRequestConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + AssetBundleCreateRequestConfiguredSource nextNode; + public ref AssetBundleCreateRequestConfiguredSource NextNode => ref nextNode; + + static AssetBundleCreateRequestConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(AssetBundleCreateRequestConfiguredSource), () => pool.Size); + } + + AssetBundleCreateRequest asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + AssetBundleCreateRequestConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(AssetBundleCreateRequest asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new AssetBundleCreateRequestConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (AssetBundleCreateRequestConfiguredSource)state; + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public AssetBundle GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + core.TrySetResult(asyncOperation.assetBundle); + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else + { + core.TrySetResult(asyncOperation.assetBundle); + } + } + } + + #endregion +#endif + +#if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT) + #region UnityWebRequestAsyncOperation + + public static UnityWebRequestAsyncOperationAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOperation) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + return new UnityWebRequestAsyncOperationAwaiter(asyncOperation); + } + + public static UniTask WithCancellation(this UnityWebRequestAsyncOperation asyncOperation, CancellationToken cancellationToken) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken); + } + + public static UniTask WithCancellation(this UnityWebRequestAsyncOperation asyncOperation, CancellationToken cancellationToken, bool cancelImmediately) + { + return ToUniTask(asyncOperation, cancellationToken: cancellationToken, cancelImmediately: cancelImmediately); + } + + public static UniTask ToUniTask(this UnityWebRequestAsyncOperation asyncOperation, IProgress progress = null, PlayerLoopTiming timing = PlayerLoopTiming.Update, CancellationToken cancellationToken = default(CancellationToken), bool cancelImmediately = false) + { + Error.ThrowArgumentNullException(asyncOperation, nameof(asyncOperation)); + if (cancellationToken.IsCancellationRequested) return UniTask.FromCanceled(cancellationToken); + if (asyncOperation.isDone) + { + if (asyncOperation.webRequest.IsError()) + { + return UniTask.FromException(new UnityWebRequestException(asyncOperation.webRequest)); + } + return UniTask.FromResult(asyncOperation.webRequest); + } + return new UniTask(UnityWebRequestAsyncOperationConfiguredSource.Create(asyncOperation, timing, progress, cancellationToken, cancelImmediately, out var token), token); + } + + public struct UnityWebRequestAsyncOperationAwaiter : ICriticalNotifyCompletion + { + UnityWebRequestAsyncOperation asyncOperation; + Action continuationAction; + + public UnityWebRequestAsyncOperationAwaiter(UnityWebRequestAsyncOperation asyncOperation) + { + this.asyncOperation = asyncOperation; + this.continuationAction = null; + } + + public bool IsCompleted => asyncOperation.isDone; + + public UnityWebRequest GetResult() + { + if (continuationAction != null) + { + asyncOperation.completed -= continuationAction; + continuationAction = null; + var result = asyncOperation.webRequest; + asyncOperation = null; + if (result.IsError()) + { + throw new UnityWebRequestException(result); + } + return result; + } + else + { + var result = asyncOperation.webRequest; + asyncOperation = null; + if (result.IsError()) + { + throw new UnityWebRequestException(result); + } + return result; + } + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + Error.ThrowWhenContinuationIsAlreadyRegistered(continuationAction); + continuationAction = PooledDelegate.Create(continuation); + asyncOperation.completed += continuationAction; + } + } + + sealed class UnityWebRequestAsyncOperationConfiguredSource : IUniTaskSource, IPlayerLoopItem, ITaskPoolNode + { + static TaskPool pool; + UnityWebRequestAsyncOperationConfiguredSource nextNode; + public ref UnityWebRequestAsyncOperationConfiguredSource NextNode => ref nextNode; + + static UnityWebRequestAsyncOperationConfiguredSource() + { + TaskPool.RegisterSizeGetter(typeof(UnityWebRequestAsyncOperationConfiguredSource), () => pool.Size); + } + + UnityWebRequestAsyncOperation asyncOperation; + IProgress progress; + CancellationToken cancellationToken; + CancellationTokenRegistration cancellationTokenRegistration; + bool cancelImmediately; + bool completed; + + UniTaskCompletionSourceCore core; + + Action continuationAction; + + UnityWebRequestAsyncOperationConfiguredSource() + { + continuationAction = Continuation; + } + + public static IUniTaskSource Create(UnityWebRequestAsyncOperation asyncOperation, PlayerLoopTiming timing, IProgress progress, CancellationToken cancellationToken, bool cancelImmediately, out short token) + { + if (cancellationToken.IsCancellationRequested) + { + return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token); + } + + if (!pool.TryPop(out var result)) + { + result = new UnityWebRequestAsyncOperationConfiguredSource(); + } + + result.asyncOperation = asyncOperation; + result.progress = progress; + result.cancellationToken = cancellationToken; + result.cancelImmediately = cancelImmediately; + result.completed = false; + + asyncOperation.completed += result.continuationAction; + + if (cancelImmediately && cancellationToken.CanBeCanceled) + { + result.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(state => + { + var source = (UnityWebRequestAsyncOperationConfiguredSource)state; + source.asyncOperation.webRequest.Abort(); + source.core.TrySetCanceled(source.cancellationToken); + }, result); + } + + TaskTracker.TrackActiveTask(result, 3); + + PlayerLoopHelper.AddAction(timing, result); + + token = result.core.Version; + return result; + } + + public UnityWebRequest GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (!(cancelImmediately && cancellationToken.IsCancellationRequested)) + { + TryReturn(); + } + else + { + TaskTracker.RemoveTracking(this); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + public bool MoveNext() + { + // Already completed + if (completed || asyncOperation == null) + { + return false; + } + + if (cancellationToken.IsCancellationRequested) + { + asyncOperation.webRequest.Abort(); + core.TrySetCanceled(cancellationToken); + return false; + } + + if (progress != null) + { + progress.Report(asyncOperation.progress); + } + + if (asyncOperation.isDone) + { + if (asyncOperation.webRequest.IsError()) + { + core.TrySetException(new UnityWebRequestException(asyncOperation.webRequest)); + } + else + { + core.TrySetResult(asyncOperation.webRequest); + } + return false; + } + + return true; + } + + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + core.Reset(); + asyncOperation.completed -= continuationAction; + asyncOperation = default; + progress = default; + cancellationToken = default; + cancellationTokenRegistration.Dispose(); + cancelImmediately = default; + return pool.TryPush(this); + } + + void Continuation(AsyncOperation _) + { + if (completed) + { + return; + } + completed = true; + if (cancellationToken.IsCancellationRequested) + { + core.TrySetCanceled(cancellationToken); + } + else if (asyncOperation.webRequest.IsError()) + { + core.TrySetException(new UnityWebRequestException(asyncOperation.webRequest)); + } + else + { + core.TrySetResult(asyncOperation.webRequest); + } + } + } + + #endregion +#endif + + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs.meta new file mode 100644 index 00000000..6dfab815 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8cc7fd65dd1433e419be4764aeb51391 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs new file mode 100644 index 00000000..e1b11fe0 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs @@ -0,0 +1,858 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT +using System; +using System.Threading; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.UI; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UnityAsyncExtensions + { + public static AsyncUnityEventHandler GetAsyncEventHandler(this UnityEvent unityEvent, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(unityEvent, cancellationToken, false); + } + + public static UniTask OnInvokeAsync(this UnityEvent unityEvent, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(unityEvent, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnInvokeAsAsyncEnumerable(this UnityEvent unityEvent, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(unityEvent, cancellationToken); + } + + public static AsyncUnityEventHandler GetAsyncEventHandler(this UnityEvent unityEvent, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(unityEvent, cancellationToken, false); + } + + public static UniTask OnInvokeAsync(this UnityEvent unityEvent, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(unityEvent, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnInvokeAsAsyncEnumerable(this UnityEvent unityEvent, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(unityEvent, cancellationToken); + } + + public static IAsyncClickEventHandler GetAsyncClickEventHandler(this Button button) + { + return new AsyncUnityEventHandler(button.onClick, button.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncClickEventHandler GetAsyncClickEventHandler(this Button button, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(button.onClick, cancellationToken, false); + } + + public static UniTask OnClickAsync(this Button button) + { + return new AsyncUnityEventHandler(button.onClick, button.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnClickAsync(this Button button, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(button.onClick, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnClickAsAsyncEnumerable(this Button button) + { + return new UnityEventHandlerAsyncEnumerable(button.onClick, button.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnClickAsAsyncEnumerable(this Button button, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(button.onClick, cancellationToken); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Toggle toggle) + { + return new AsyncUnityEventHandler(toggle.onValueChanged, toggle.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Toggle toggle, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(toggle.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this Toggle toggle) + { + return new AsyncUnityEventHandler(toggle.onValueChanged, toggle.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this Toggle toggle, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(toggle.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Toggle toggle) + { + return new UnityEventHandlerAsyncEnumerable(toggle.onValueChanged, toggle.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Toggle toggle, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(toggle.onValueChanged, cancellationToken); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Scrollbar scrollbar) + { + return new AsyncUnityEventHandler(scrollbar.onValueChanged, scrollbar.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Scrollbar scrollbar, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(scrollbar.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this Scrollbar scrollbar) + { + return new AsyncUnityEventHandler(scrollbar.onValueChanged, scrollbar.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this Scrollbar scrollbar, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(scrollbar.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Scrollbar scrollbar) + { + return new UnityEventHandlerAsyncEnumerable(scrollbar.onValueChanged, scrollbar.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Scrollbar scrollbar, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(scrollbar.onValueChanged, cancellationToken); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this ScrollRect scrollRect) + { + return new AsyncUnityEventHandler(scrollRect.onValueChanged, scrollRect.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this ScrollRect scrollRect, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(scrollRect.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this ScrollRect scrollRect) + { + return new AsyncUnityEventHandler(scrollRect.onValueChanged, scrollRect.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this ScrollRect scrollRect, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(scrollRect.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this ScrollRect scrollRect) + { + return new UnityEventHandlerAsyncEnumerable(scrollRect.onValueChanged, scrollRect.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this ScrollRect scrollRect, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(scrollRect.onValueChanged, cancellationToken); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Slider slider) + { + return new AsyncUnityEventHandler(slider.onValueChanged, slider.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Slider slider, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(slider.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this Slider slider) + { + return new AsyncUnityEventHandler(slider.onValueChanged, slider.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this Slider slider, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(slider.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Slider slider) + { + return new UnityEventHandlerAsyncEnumerable(slider.onValueChanged, slider.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Slider slider, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(slider.onValueChanged, cancellationToken); + } + + public static IAsyncEndEditEventHandler GetAsyncEndEditEventHandler(this InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncEndEditEventHandler GetAsyncEndEditEventHandler(this InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, cancellationToken, false); + } + + public static UniTask OnEndEditAsync(this InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnEndEditAsync(this InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onEndEdit, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnEndEditAsAsyncEnumerable(this InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onEndEdit, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnEndEditAsAsyncEnumerable(this InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onEndEdit, cancellationToken); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, inputField.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this InputField inputField) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, inputField.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this InputField inputField, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(inputField.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this InputField inputField) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onValueChanged, inputField.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this InputField inputField, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(inputField.onValueChanged, cancellationToken); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Dropdown dropdown) + { + return new AsyncUnityEventHandler(dropdown.onValueChanged, dropdown.GetCancellationTokenOnDestroy(), false); + } + + public static IAsyncValueChangedEventHandler GetAsyncValueChangedEventHandler(this Dropdown dropdown, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(dropdown.onValueChanged, cancellationToken, false); + } + + public static UniTask OnValueChangedAsync(this Dropdown dropdown) + { + return new AsyncUnityEventHandler(dropdown.onValueChanged, dropdown.GetCancellationTokenOnDestroy(), true).OnInvokeAsync(); + } + + public static UniTask OnValueChangedAsync(this Dropdown dropdown, CancellationToken cancellationToken) + { + return new AsyncUnityEventHandler(dropdown.onValueChanged, cancellationToken, true).OnInvokeAsync(); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Dropdown dropdown) + { + return new UnityEventHandlerAsyncEnumerable(dropdown.onValueChanged, dropdown.GetCancellationTokenOnDestroy()); + } + + public static IUniTaskAsyncEnumerable OnValueChangedAsAsyncEnumerable(this Dropdown dropdown, CancellationToken cancellationToken) + { + return new UnityEventHandlerAsyncEnumerable(dropdown.onValueChanged, cancellationToken); + } + } + + public interface IAsyncClickEventHandler : IDisposable + { + UniTask OnClickAsync(); + } + + public interface IAsyncValueChangedEventHandler : IDisposable + { + UniTask OnValueChangedAsync(); + } + + public interface IAsyncEndEditEventHandler : IDisposable + { + UniTask OnEndEditAsync(); + } + + // for TMP_PRO + + public interface IAsyncEndTextSelectionEventHandler : IDisposable + { + UniTask OnEndTextSelectionAsync(); + } + + public interface IAsyncTextSelectionEventHandler : IDisposable + { + UniTask OnTextSelectionAsync(); + } + + public interface IAsyncDeselectEventHandler : IDisposable + { + UniTask OnDeselectAsync(); + } + + public interface IAsyncSelectEventHandler : IDisposable + { + UniTask OnSelectAsync(); + } + + public interface IAsyncSubmitEventHandler : IDisposable + { + UniTask OnSubmitAsync(); + } + + internal class TextSelectionEventConverter : UnityEvent<(string, int, int)>, IDisposable + { + readonly UnityEvent innerEvent; + readonly UnityAction invokeDelegate; + + + public TextSelectionEventConverter(UnityEvent unityEvent) + { + this.innerEvent = unityEvent; + this.invokeDelegate = InvokeCore; + + innerEvent.AddListener(invokeDelegate); + } + + void InvokeCore(string item1, int item2, int item3) + { + Invoke((item1, item2, item3)); + } + + public void Dispose() + { + innerEvent.RemoveListener(invokeDelegate); + } + } + + public class AsyncUnityEventHandler : IUniTaskSource, IDisposable, IAsyncClickEventHandler + { + static Action cancellationCallback = CancellationCallback; + + readonly UnityAction action; + readonly UnityEvent unityEvent; + + CancellationToken cancellationToken; + CancellationTokenRegistration registration; + bool isDisposed; + bool callOnce; + + UniTaskCompletionSourceCore core; + + public AsyncUnityEventHandler(UnityEvent unityEvent, CancellationToken cancellationToken, bool callOnce) + { + this.cancellationToken = cancellationToken; + if (cancellationToken.IsCancellationRequested) + { + isDisposed = true; + return; + } + + this.action = Invoke; + this.unityEvent = unityEvent; + this.callOnce = callOnce; + + unityEvent.AddListener(action); + + if (cancellationToken.CanBeCanceled) + { + registration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + + TaskTracker.TrackActiveTask(this, 3); + } + + public UniTask OnInvokeAsync() + { + core.Reset(); + if (isDisposed) + { + core.TrySetCanceled(this.cancellationToken); + } + return new UniTask(this, core.Version); + } + + void Invoke() + { + core.TrySetResult(AsyncUnit.Default); + } + + static void CancellationCallback(object state) + { + var self = (AsyncUnityEventHandler)state; + self.Dispose(); + } + + public void Dispose() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + registration.Dispose(); + if (unityEvent != null) + { + unityEvent.RemoveListener(action); + } + core.TrySetCanceled(cancellationToken); + } + } + + UniTask IAsyncClickEventHandler.OnClickAsync() + { + return OnInvokeAsync(); + } + + void IUniTaskSource.GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + if (callOnce) + { + Dispose(); + } + } + } + + UniTaskStatus IUniTaskSource.GetStatus(short token) + { + return core.GetStatus(token); + } + + UniTaskStatus IUniTaskSource.UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public class AsyncUnityEventHandler : IUniTaskSource, IDisposable, IAsyncValueChangedEventHandler, IAsyncEndEditEventHandler + , IAsyncEndTextSelectionEventHandler, IAsyncTextSelectionEventHandler, IAsyncDeselectEventHandler, IAsyncSelectEventHandler, IAsyncSubmitEventHandler + { + static Action cancellationCallback = CancellationCallback; + + readonly UnityAction action; + readonly UnityEvent unityEvent; + + CancellationToken cancellationToken; + CancellationTokenRegistration registration; + bool isDisposed; + bool callOnce; + + UniTaskCompletionSourceCore core; + + public AsyncUnityEventHandler(UnityEvent unityEvent, CancellationToken cancellationToken, bool callOnce) + { + this.cancellationToken = cancellationToken; + if (cancellationToken.IsCancellationRequested) + { + isDisposed = true; + return; + } + + this.action = Invoke; + this.unityEvent = unityEvent; + this.callOnce = callOnce; + + unityEvent.AddListener(action); + + if (cancellationToken.CanBeCanceled) + { + registration = cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationCallback, this); + } + + TaskTracker.TrackActiveTask(this, 3); + } + + public UniTask OnInvokeAsync() + { + core.Reset(); + if (isDisposed) + { + core.TrySetCanceled(this.cancellationToken); + } + return new UniTask(this, core.Version); + } + + void Invoke(T result) + { + core.TrySetResult(result); + } + + static void CancellationCallback(object state) + { + var self = (AsyncUnityEventHandler)state; + self.Dispose(); + } + + public void Dispose() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + registration.Dispose(); + if (unityEvent != null) + { + // Dispose inner delegate for TextSelectionEventConverter + if (unityEvent is IDisposable disp) + { + disp.Dispose(); + } + + unityEvent.RemoveListener(action); + } + + core.TrySetCanceled(); + } + } + + UniTask IAsyncValueChangedEventHandler.OnValueChangedAsync() + { + return OnInvokeAsync(); + } + + UniTask IAsyncEndEditEventHandler.OnEndEditAsync() + { + return OnInvokeAsync(); + } + + UniTask IAsyncEndTextSelectionEventHandler.OnEndTextSelectionAsync() + { + return OnInvokeAsync(); + } + + UniTask IAsyncTextSelectionEventHandler.OnTextSelectionAsync() + { + return OnInvokeAsync(); + } + + UniTask IAsyncDeselectEventHandler.OnDeselectAsync() + { + return OnInvokeAsync(); + } + + UniTask IAsyncSelectEventHandler.OnSelectAsync() + { + return OnInvokeAsync(); + } + + UniTask IAsyncSubmitEventHandler.OnSubmitAsync() + { + return OnInvokeAsync(); + } + + T IUniTaskSource.GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + if (callOnce) + { + Dispose(); + } + } + } + + void IUniTaskSource.GetResult(short token) + { + ((IUniTaskSource)this).GetResult(token); + } + + UniTaskStatus IUniTaskSource.GetStatus(short token) + { + return core.GetStatus(token); + } + + UniTaskStatus IUniTaskSource.UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + void IUniTaskSource.OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + } + + public class UnityEventHandlerAsyncEnumerable : IUniTaskAsyncEnumerable + { + readonly UnityEvent unityEvent; + readonly CancellationToken cancellationToken1; + + public UnityEventHandlerAsyncEnumerable(UnityEvent unityEvent, CancellationToken cancellationToken) + { + this.unityEvent = unityEvent; + this.cancellationToken1 = cancellationToken; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + if (this.cancellationToken1 == cancellationToken) + { + return new UnityEventHandlerAsyncEnumerator(unityEvent, this.cancellationToken1, CancellationToken.None); + } + else + { + return new UnityEventHandlerAsyncEnumerator(unityEvent, this.cancellationToken1, cancellationToken); + } + } + + class UnityEventHandlerAsyncEnumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action cancel1 = OnCanceled1; + static readonly Action cancel2 = OnCanceled2; + + readonly UnityEvent unityEvent; + CancellationToken cancellationToken1; + CancellationToken cancellationToken2; + + UnityAction unityAction; + CancellationTokenRegistration registration1; + CancellationTokenRegistration registration2; + bool isDisposed; + + public UnityEventHandlerAsyncEnumerator(UnityEvent unityEvent, CancellationToken cancellationToken1, CancellationToken cancellationToken2) + { + this.unityEvent = unityEvent; + this.cancellationToken1 = cancellationToken1; + this.cancellationToken2 = cancellationToken2; + } + + public AsyncUnit Current => default; + + public UniTask MoveNextAsync() + { + cancellationToken1.ThrowIfCancellationRequested(); + cancellationToken2.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (unityAction == null) + { + unityAction = Invoke; + + TaskTracker.TrackActiveTask(this, 3); + unityEvent.AddListener(unityAction); + if (cancellationToken1.CanBeCanceled) + { + registration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(cancel1, this); + } + if (cancellationToken2.CanBeCanceled) + { + registration2 = cancellationToken2.RegisterWithoutCaptureExecutionContext(cancel2, this); + } + } + + return new UniTask(this, completionSource.Version); + } + + void Invoke() + { + completionSource.TrySetResult(true); + } + + static void OnCanceled1(object state) + { + var self = (UnityEventHandlerAsyncEnumerator)state; + try + { + self.completionSource.TrySetCanceled(self.cancellationToken1); + } + finally + { + self.DisposeAsync().Forget(); + } + } + + static void OnCanceled2(object state) + { + var self = (UnityEventHandlerAsyncEnumerator)state; + try + { + self.completionSource.TrySetCanceled(self.cancellationToken2); + } + finally + { + self.DisposeAsync().Forget(); + } + } + + public UniTask DisposeAsync() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + registration1.Dispose(); + registration2.Dispose(); + unityEvent.RemoveListener(unityAction); + + completionSource.TrySetCanceled(); + } + + return default; + } + } + } + + public class UnityEventHandlerAsyncEnumerable : IUniTaskAsyncEnumerable + { + readonly UnityEvent unityEvent; + readonly CancellationToken cancellationToken1; + + public UnityEventHandlerAsyncEnumerable(UnityEvent unityEvent, CancellationToken cancellationToken) + { + this.unityEvent = unityEvent; + this.cancellationToken1 = cancellationToken; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + if (this.cancellationToken1 == cancellationToken) + { + return new UnityEventHandlerAsyncEnumerator(unityEvent, this.cancellationToken1, CancellationToken.None); + } + else + { + return new UnityEventHandlerAsyncEnumerator(unityEvent, this.cancellationToken1, cancellationToken); + } + } + + class UnityEventHandlerAsyncEnumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action cancel1 = OnCanceled1; + static readonly Action cancel2 = OnCanceled2; + + readonly UnityEvent unityEvent; + CancellationToken cancellationToken1; + CancellationToken cancellationToken2; + + UnityAction unityAction; + CancellationTokenRegistration registration1; + CancellationTokenRegistration registration2; + bool isDisposed; + + public UnityEventHandlerAsyncEnumerator(UnityEvent unityEvent, CancellationToken cancellationToken1, CancellationToken cancellationToken2) + { + this.unityEvent = unityEvent; + this.cancellationToken1 = cancellationToken1; + this.cancellationToken2 = cancellationToken2; + } + + public T Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken1.ThrowIfCancellationRequested(); + cancellationToken2.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (unityAction == null) + { + unityAction = Invoke; + + TaskTracker.TrackActiveTask(this, 3); + unityEvent.AddListener(unityAction); + if (cancellationToken1.CanBeCanceled) + { + registration1 = cancellationToken1.RegisterWithoutCaptureExecutionContext(cancel1, this); + } + if (cancellationToken2.CanBeCanceled) + { + registration2 = cancellationToken2.RegisterWithoutCaptureExecutionContext(cancel2, this); + } + } + + return new UniTask(this, completionSource.Version); + } + + void Invoke(T value) + { + Current = value; + completionSource.TrySetResult(true); + } + + static void OnCanceled1(object state) + { + var self = (UnityEventHandlerAsyncEnumerator)state; + try + { + self.completionSource.TrySetCanceled(self.cancellationToken1); + } + finally + { + self.DisposeAsync().Forget(); + } + } + + static void OnCanceled2(object state) + { + var self = (UnityEventHandlerAsyncEnumerator)state; + try + { + self.completionSource.TrySetCanceled(self.cancellationToken2); + } + finally + { + self.DisposeAsync().Forget(); + } + } + + public UniTask DisposeAsync() + { + if (!isDisposed) + { + isDisposed = true; + TaskTracker.RemoveTracking(this); + registration1.Dispose(); + registration2.Dispose(); + if (unityEvent is IDisposable disp) + { + disp.Dispose(); + } + unityEvent.RemoveListener(unityAction); + + completionSource.TrySetCanceled(); + } + + return default; + } + } + } +} + +#endif diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs.meta new file mode 100644 index 00000000..90c5d515 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6804799fba2376d4099561d176101aff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAwaitableExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAwaitableExtensions.cs new file mode 100644 index 00000000..4580da3a --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAwaitableExtensions.cs @@ -0,0 +1,17 @@ +#if UNITY_2023_1_OR_NEWER +namespace Cysharp.Threading.Tasks +{ + public static class UnityAwaitableExtensions + { + public static async UniTask AsUniTask(this UnityEngine.Awaitable awaitable) + { + await awaitable; + } + + public static async UniTask AsUniTask(this UnityEngine.Awaitable awaitable) + { + return await awaitable; + } + } +} +#endif diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAwaitableExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAwaitableExtensions.cs.meta new file mode 100644 index 00000000..08752a42 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityAwaitableExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c29533c9e4284dee914b71a6579ea274 +timeCreated: 1698895807 \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityBindingExtensions.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityBindingExtensions.cs new file mode 100644 index 00000000..269fee2b --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityBindingExtensions.cs @@ -0,0 +1,245 @@ +using System; +using System.Threading; +using UnityEngine; +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT +using UnityEngine.UI; +#endif + +namespace Cysharp.Threading.Tasks +{ + public static class UnityBindingExtensions + { +#if !UNITY_2019_1_OR_NEWER || UNITASK_UGUI_SUPPORT + // -> Text + + public static void BindTo(this IUniTaskAsyncEnumerable source, UnityEngine.UI.Text text, bool rebindOnError = true) + { + BindToCore(source, text, text.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + public static void BindTo(this IUniTaskAsyncEnumerable source, UnityEngine.UI.Text text, CancellationToken cancellationToken, bool rebindOnError = true) + { + BindToCore(source, text, cancellationToken, rebindOnError).Forget(); + } + + static async UniTaskVoid BindToCore(IUniTaskAsyncEnumerable source, UnityEngine.UI.Text text, CancellationToken cancellationToken, bool rebindOnError) + { + var repeat = false; + BIND_AGAIN: + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + bool moveNext; + try + { + moveNext = await e.MoveNextAsync(); + repeat = false; + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + if (rebindOnError && !repeat) + { + repeat = true; + goto BIND_AGAIN; + } + else + { + throw; + } + } + + if (!moveNext) return; + + text.text = e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // -> Text + + public static void BindTo(this IUniTaskAsyncEnumerable source, UnityEngine.UI.Text text, bool rebindOnError = true) + { + BindToCore(source, text, text.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + public static void BindTo(this IUniTaskAsyncEnumerable source, UnityEngine.UI.Text text, CancellationToken cancellationToken, bool rebindOnError = true) + { + BindToCore(source, text, cancellationToken, rebindOnError).Forget(); + } + + public static void BindTo(this AsyncReactiveProperty source, UnityEngine.UI.Text text, bool rebindOnError = true) + { + BindToCore(source, text, text.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + static async UniTaskVoid BindToCore(IUniTaskAsyncEnumerable source, UnityEngine.UI.Text text, CancellationToken cancellationToken, bool rebindOnError) + { + var repeat = false; + BIND_AGAIN: + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + bool moveNext; + try + { + moveNext = await e.MoveNextAsync(); + repeat = false; + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + if (rebindOnError && !repeat) + { + repeat = true; + goto BIND_AGAIN; + } + else + { + throw; + } + } + + if (!moveNext) return; + + text.text = e.Current.ToString(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // -> Selectable + + public static void BindTo(this IUniTaskAsyncEnumerable source, Selectable selectable, bool rebindOnError = true) + { + BindToCore(source, selectable, selectable.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + public static void BindTo(this IUniTaskAsyncEnumerable source, Selectable selectable, CancellationToken cancellationToken, bool rebindOnError = true) + { + BindToCore(source, selectable, cancellationToken, rebindOnError).Forget(); + } + + static async UniTaskVoid BindToCore(IUniTaskAsyncEnumerable source, Selectable selectable, CancellationToken cancellationToken, bool rebindOnError) + { + var repeat = false; + BIND_AGAIN: + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + bool moveNext; + try + { + moveNext = await e.MoveNextAsync(); + repeat = false; + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + if (rebindOnError && !repeat) + { + repeat = true; + goto BIND_AGAIN; + } + else + { + throw; + } + } + + if (!moveNext) return; + + + selectable.interactable = e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } +#endif + + // -> Action + + public static void BindTo(this IUniTaskAsyncEnumerable source, TObject monoBehaviour, Action bindAction, bool rebindOnError = true) + where TObject : MonoBehaviour + { + BindToCore(source, monoBehaviour, bindAction, monoBehaviour.GetCancellationTokenOnDestroy(), rebindOnError).Forget(); + } + + public static void BindTo(this IUniTaskAsyncEnumerable source, TObject bindTarget, Action bindAction, CancellationToken cancellationToken, bool rebindOnError = true) + { + BindToCore(source, bindTarget, bindAction, cancellationToken, rebindOnError).Forget(); + } + + static async UniTaskVoid BindToCore(IUniTaskAsyncEnumerable source, TObject bindTarget, Action bindAction, CancellationToken cancellationToken, bool rebindOnError) + { + var repeat = false; + BIND_AGAIN: + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + bool moveNext; + try + { + moveNext = await e.MoveNextAsync(); + repeat = false; + } + catch (Exception ex) + { + if (ex is OperationCanceledException) return; + + if (rebindOnError && !repeat) + { + repeat = true; + goto BIND_AGAIN; + } + else + { + throw; + } + } + + if (!moveNext) return; + + bindAction(bindTarget, e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityBindingExtensions.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityBindingExtensions.cs.meta new file mode 100644 index 00000000..3fae798e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityBindingExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 090b20e3528552b4a8d751f7df525c2b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityWebRequestException.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityWebRequestException.cs new file mode 100644 index 00000000..95857694 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityWebRequestException.cs @@ -0,0 +1,67 @@ +#if ENABLE_UNITYWEBREQUEST && (!UNITY_2019_1_OR_NEWER || UNITASK_WEBREQUEST_SUPPORT) + +using System; +using System.Collections.Generic; +using UnityEngine.Networking; + +namespace Cysharp.Threading.Tasks +{ + public class UnityWebRequestException : Exception + { + public UnityWebRequest UnityWebRequest { get; } +#if UNITY_2020_2_OR_NEWER + public UnityWebRequest.Result Result { get; } +#else + public bool IsNetworkError { get; } + public bool IsHttpError { get; } +#endif + public string Error { get; } + public string Text { get; } + public long ResponseCode { get; } + public Dictionary ResponseHeaders { get; } + + string msg; + + public UnityWebRequestException(UnityWebRequest unityWebRequest) + { + this.UnityWebRequest = unityWebRequest; +#if UNITY_2020_2_OR_NEWER + this.Result = unityWebRequest.result; +#else + this.IsNetworkError = unityWebRequest.isNetworkError; + this.IsHttpError = unityWebRequest.isHttpError; +#endif + this.Error = unityWebRequest.error; + this.ResponseCode = unityWebRequest.responseCode; + if (UnityWebRequest.downloadHandler != null) + { + if (unityWebRequest.downloadHandler is DownloadHandlerBuffer dhb) + { + this.Text = dhb.text; + } + } + this.ResponseHeaders = unityWebRequest.GetResponseHeaders(); + } + + public override string Message + { + get + { + if (msg == null) + { + if(!string.IsNullOrWhiteSpace(Text)) + { + msg = Error + Environment.NewLine + Text; + } + else + { + msg = Error; + } + } + return msg; + } + } + } +} + +#endif \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/UnityWebRequestException.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityWebRequestException.cs.meta new file mode 100644 index 00000000..50c475e8 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/UnityWebRequestException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 013a499e522703a42962a779b4d9850c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/_InternalVisibleTo.cs b/Fantasy.Unity/Plugins/UniTask/Runtime/_InternalVisibleTo.cs new file mode 100644 index 00000000..ab7c10c9 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/_InternalVisibleTo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("UniTask.Linq")] +[assembly: InternalsVisibleTo("UniTask.Addressables")] +[assembly: InternalsVisibleTo("UniTask.DOTween")] +[assembly: InternalsVisibleTo("UniTask.TextMeshPro")] \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UniTask/Runtime/_InternalVisibleTo.cs.meta b/Fantasy.Unity/Plugins/UniTask/Runtime/_InternalVisibleTo.cs.meta new file mode 100644 index 00000000..2ec6cd36 --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/Runtime/_InternalVisibleTo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8507e97eb606fad4b99c6edf92e19cb8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UniTask/package.json b/Fantasy.Unity/Plugins/UniTask/package.json new file mode 100644 index 00000000..a2ef568e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/package.json @@ -0,0 +1,12 @@ +{ + "name": "com.cysharp.unitask", + "displayName": "UniTask", + "author": { "name": "Cysharp, Inc.", "url": "https://cysharp.co.jp/en/" }, + "version": "2.5.10", + "unity": "2018.4", + "description": "Provides an efficient async/await integration to Unity.", + "keywords": [ "async/await", "async", "Task", "UniTask" ], + "license": "MIT", + "category": "Task", + "dependencies": {} +} diff --git a/Fantasy.Unity/Plugins/UniTask/package.json.meta b/Fantasy.Unity/Plugins/UniTask/package.json.meta new file mode 100644 index 00000000..65439e6e --- /dev/null +++ b/Fantasy.Unity/Plugins/UniTask/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d1a9a71f68bb0d04db91ddaa3329abf9 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UnitaskExtension.meta b/Fantasy.Unity/Plugins/UnitaskExtension.meta new file mode 100644 index 00000000..a6a14c2d --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ef4dab7494475764fa101cb753a5ea11 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UnitaskExtension/AutoResetUniTaskCompletionSourcePlus.cs b/Fantasy.Unity/Plugins/UnitaskExtension/AutoResetUniTaskCompletionSourcePlus.cs new file mode 100644 index 00000000..5d5569cc --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension/AutoResetUniTaskCompletionSourcePlus.cs @@ -0,0 +1,340 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public class AutoResetUniTaskCompletionSourcePlus : IUniTaskSource, ITaskPoolNode, IPromise + { + static TaskPool pool; + AutoResetUniTaskCompletionSourcePlus nextNode; + event Action onExceptionAction; + event Action onCancelAction; + event Action onResultAction; + public ref AutoResetUniTaskCompletionSourcePlus NextNode => ref nextNode; + + static AutoResetUniTaskCompletionSourcePlus() + { + TaskPool.RegisterSizeGetter(typeof(AutoResetUniTaskCompletionSourcePlus), () => pool.Size); + } + + UniTaskCompletionSourceCore core; + + AutoResetUniTaskCompletionSourcePlus() + { + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus Create() + { + if (!pool.TryPop(out var result)) + { + result = new AutoResetUniTaskCompletionSourcePlus(); + } + TaskTracker.TrackActiveTask(result, 2); + return result; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus CreateFromCanceled(CancellationToken cancellationToken, out short token) + { + var source = Create(); + source.TrySetCanceled(cancellationToken); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus CreateFromException(Exception exception, out short token) + { + var source = Create(); + source.TrySetException(exception); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus CreateCompleted(out short token) + { + var source = Create(); + source.TrySetResult(); + token = source.core.Version; + return source; + } + + public void AddOnCancelAction(Action action) + { + onCancelAction += action; + } + + public void AddOnExceptionAction(Action action) + { + onExceptionAction += action; + } + + public void AddOnResultAction(Action action) + { + onResultAction += action; + } + + public void RemoveOnCancelAction(Action action) + { + onCancelAction -= action; + } + + public void RemoveOnExceptionAction(Action action) + { + onExceptionAction -= action; + } + + public void RemoveOnResultAction(Action action) + { + onResultAction -= action; + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, core.Version); + } + } + + [DebuggerHidden] + public bool TrySetResult() + { + onResultAction?.Invoke(); + onResultAction = null; + return core.TrySetResult(AsyncUnit.Default); + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + onCancelAction?.Invoke(); + onCancelAction = null; + return core.TrySetCanceled(cancellationToken); + } + + [DebuggerHidden] + public bool TrySetException(Exception exception) + { + onExceptionAction?.Invoke(); + onExceptionAction = null; + return core.TrySetException(exception); + } + + [DebuggerHidden] + public void GetResult(short token) + { + try + { + core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + [DebuggerHidden] + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + onExceptionAction = null; + onCancelAction = null; + onResultAction = null; + core.Reset(); + return pool.TryPush(this); + } + } + + public class AutoResetUniTaskCompletionSourcePlus : IUniTaskSource, ITaskPoolNode>, IPromise + { + static TaskPool> pool; + AutoResetUniTaskCompletionSourcePlus nextNode; + event Action onExceptionAction; + event Action onCancelAction; + event Action onResultAction; + public ref AutoResetUniTaskCompletionSourcePlus NextNode => ref nextNode; + + static AutoResetUniTaskCompletionSourcePlus() + { + TaskPool.RegisterSizeGetter(typeof(AutoResetUniTaskCompletionSourcePlus), () => pool.Size); + } + + UniTaskCompletionSourceCore core; + + AutoResetUniTaskCompletionSourcePlus() + { + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus Create() + { + if (!pool.TryPop(out var result)) + { + result = new AutoResetUniTaskCompletionSourcePlus(); + } + TaskTracker.TrackActiveTask(result, 2); + return result; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus CreateFromCanceled(CancellationToken cancellationToken, out short token) + { + var source = Create(); + source.TrySetCanceled(cancellationToken); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus CreateFromException(Exception exception, out short token) + { + var source = Create(); + source.TrySetException(exception); + token = source.core.Version; + return source; + } + + [DebuggerHidden] + public static AutoResetUniTaskCompletionSourcePlus CreateFromResult(T result, out short token) + { + var source = Create(); + source.TrySetResult(result); + token = source.core.Version; + return source; + } + + public void AddOnCancelAction(Action action) + { + onCancelAction += action; + } + + public void AddOnExceptionAction(Action action) + { + onExceptionAction += action; + } + + public void AddOnResultAction(Action action) + { + onResultAction += action; + } + + public void RemoveOnCancelAction(Action action) + { + onCancelAction -= action; + } + + public void RemoveOnExceptionAction(Action action) + { + onExceptionAction -= action; + } + + public void RemoveOnResultAction(Action action) + { + onResultAction -= action; + } + + public UniTask Task + { + [DebuggerHidden] + get + { + return new UniTask(this, core.Version); + } + } + + [DebuggerHidden] + public bool TrySetResult(T result) + { + onResultAction?.Invoke(); + onResultAction = null; + return core.TrySetResult(result); + } + + [DebuggerHidden] + public bool TrySetCanceled(CancellationToken cancellationToken = default) + { + onCancelAction?.Invoke(); + onCancelAction = null; + return core.TrySetCanceled(cancellationToken); + } + + [DebuggerHidden] + public bool TrySetException(Exception exception) + { + onExceptionAction?.Invoke(); + onExceptionAction = null; + return core.TrySetException(exception); + } + + [DebuggerHidden] + public T GetResult(short token) + { + try + { + return core.GetResult(token); + } + finally + { + TryReturn(); + } + } + + [DebuggerHidden] + void IUniTaskSource.GetResult(short token) + { + GetResult(token); + } + + [DebuggerHidden] + public UniTaskStatus GetStatus(short token) + { + return core.GetStatus(token); + } + + [DebuggerHidden] + public UniTaskStatus UnsafeGetStatus() + { + return core.UnsafeGetStatus(); + } + + [DebuggerHidden] + public void OnCompleted(Action continuation, object state, short token) + { + core.OnCompleted(continuation, state, token); + } + + [DebuggerHidden] + bool TryReturn() + { + TaskTracker.RemoveTracking(this); + onExceptionAction = null; + onCancelAction = null; + onResultAction = null; + core.Reset(); + return pool.TryPush(this); + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UnitaskExtension/AutoResetUniTaskCompletionSourcePlus.cs.meta b/Fantasy.Unity/Plugins/UnitaskExtension/AutoResetUniTaskCompletionSourcePlus.cs.meta new file mode 100644 index 00000000..f95da4dd --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension/AutoResetUniTaskCompletionSourcePlus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac4248d368679ee4d9b77e615223d717 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Cancel.cs b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Cancel.cs new file mode 100644 index 00000000..22d2c0fb --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Cancel.cs @@ -0,0 +1,150 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public static partial class UniTaskExtension + { + public static void AttachCancellation(this AutoResetUniTaskCompletionSourcePlus tcs, CancellationToken token) + { + if (!token.CanBeCanceled) + return; + + void TrySetCanceled() + { + tcs.TrySetCanceled(token); + } + + CancellationTokenRegistration ctr = token.RegisterWithoutCaptureExecutionContext(TrySetCanceled); + + void Dispose() + { + ctr.Dispose(); + } + + tcs.AddOnCancelAction(Dispose); + tcs.AddOnExceptionAction(Dispose); + tcs.AddOnResultAction(Dispose); + } + + public static void AttachCancellation(this AutoResetUniTaskCompletionSourcePlus tcs, CancellationToken token) + { + if (!token.CanBeCanceled) + return; + + void TrySetCanceled() + { + tcs.TrySetCanceled(token); + } + + CancellationTokenRegistration ctr = token.RegisterWithoutCaptureExecutionContext(TrySetCanceled); + + void Dispose() + { + ctr.Dispose(); + } + + tcs.AddOnCancelAction(Dispose); + tcs.AddOnExceptionAction(Dispose); + tcs.AddOnResultAction(Dispose); + } + + public static UniTask AttachCancellation(this UniTask task, CancellationToken token, Action cancelAction = null) + { + if (token.IsCancellationRequested) + { + throw new Exception("Can't attach canceled CancellationToken!"); + } + if (token.CanBeCanceled) + { + var tcs = AutoResetUniTaskCompletionSource.Create(); + + void CancelAction() + { + cancelAction?.Invoke(); + tcs.TrySetCanceled(token); + } + + async UniTaskVoid RunTask() + { + var ctr = token.RegisterWithoutCaptureExecutionContext(CancelAction); + try + { + await task; + tcs.TrySetResult(); + } + catch (Exception ex) + { + tcs.TrySetException(ex); + } + finally + { + ctr.Dispose(); + } + } + + RunTask().Forget(); + return tcs.Task; + } + return task; + } + + public static UniTask AttachCancellation(this UniTask task, CancellationToken token, Action cancelAction = null) + { + if (token.IsCancellationRequested) + { + throw new Exception("Can't attach canceled CancellationToken!"); + } + if (token.CanBeCanceled) + { + var tcs = AutoResetUniTaskCompletionSource.Create(); + + void CancelAction() + { + cancelAction?.Invoke(); + tcs.TrySetCanceled(token); + } + + async UniTaskVoid RunTask() + { + var ctr = token.RegisterWithoutCaptureExecutionContext(CancelAction); + try + { + T result = await task; + tcs.TrySetResult(result); + } + catch (Exception ex) + { + tcs.TrySetException(ex); + } + finally + { + ctr.Dispose(); + } + } + + RunTask().Forget(); + return tcs.Task; + } + return task; + } + + public static async UniTask RunCancelAsync(this UniTask task, Action cancelAction) + { + bool canceled = await task.SuppressCancellationThrow(); + if (canceled) + { + cancelAction.Invoke(); + } + } + + public static async UniTask RunCancelAsync(this UniTask task, Action cancelAction) + { + (bool canceled, _) = await task.SuppressCancellationThrow(); + if (canceled) + { + cancelAction.Invoke(); + } + } + } +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Cancel.cs.meta b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Cancel.cs.meta new file mode 100644 index 00000000..d66590ac --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Cancel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ac49ab40c32fd14d808187a5e5a6df1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Extension.asmdef b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Extension.asmdef new file mode 100644 index 00000000..55881fb3 --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Extension.asmdef @@ -0,0 +1,16 @@ +{ + "name": "UniTask.Extension", + "rootNamespace": "", + "references": [ + "GUID:f51ebe6a0ceec4240a699833d6309b23" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Extension.asmdef.meta b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Extension.asmdef.meta new file mode 100644 index 00000000..e7604233 --- /dev/null +++ b/Fantasy.Unity/Plugins/UnitaskExtension/UniTask.Extension.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 77d6c8c98758f884fbc6cb1c9bfb5924 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: