diff --git a/.github/workflows/build-debug.yml b/.github/workflows/build-debug.yml index 854fbcd..3e8f8e0 100644 --- a/.github/workflows/build-debug.yml +++ b/.github/workflows/build-debug.yml @@ -17,75 +17,6 @@ jobs: - uses: Cysharp/Actions/.github/actions/setup-dotnet@main with: dotnet-version: | - 5.0.x - 6.0.x + 9.0.x - run: dotnet build -c Debug - - run: dotnet test -c Debug --no-build - - build-unity: - if: ${{ ((github.event_name == 'push' && github.repository_owner == 'Cysharp') || startsWith(github.event.pull_request.head.label, 'Cysharp:')) && github.triggering_actor != 'dependabot[bot]' }} - strategy: - fail-fast: false - max-parallel: 2 - matrix: - unity: ["2021.3.41f1", "2022.3.39f1", "6000.0.12f1"] # Test with LTS - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - name: Load secrets - id: op-load-secret - uses: 1password/load-secrets-action@v2 - with: - export-env: false - env: - OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN_PUBLIC }} - UNITY_EMAIL: "op://GitHubActionsPublic/UNITY_LICENSE/username" - UNITY_PASSWORD: "op://GitHubActionsPublic/UNITY_LICENSE/credential" - UNITY_SERIAL: "op://GitHubActionsPublic/UNITY_LICENSE/serial" - - - uses: actions/checkout@v4 - - # Execute scripts: Export Package - # /opt/Unity/Editor/Unity -quit -batchmode -nographics -silent-crashes -logFile -projectPath . -executeMethod PackageExporter.Export - - name: Build Unity (.unitypacakge) - if: ${{ startsWith(matrix.unity, '2021') }} # only execute once - uses: Cysharp/Actions/.github/actions/unity-builder@main - env: - UNITY_EMAIL: ${{ steps.op-load-secret.outputs.UNITY_EMAIL }} - UNITY_PASSWORD: ${{ steps.op-load-secret.outputs.UNITY_PASSWORD }} - UNITY_SERIAL: ${{ steps.op-load-secret.outputs.UNITY_SERIAL }} - with: - projectPath: src/MasterMemory.Unity - unityVersion: ${{ matrix.unity }} - targetPlatform: StandaloneLinux64 - buildMethod: PackageExporter.Export - - - uses: Cysharp/Actions/.github/actions/check-metas@main # check meta files - with: - directory: src/MasterMemory.Unity - - # Execute Unittest - # /opt/Unity/Editor/Unity -quit -batchmode -nographics -silent-crashes -logFile -projectPath . -executeMethod UnitTestBuilder.BuildUnitTest /headless /ScriptBackend IL2CPP /BuildTarget StandaloneLinux64 - - name: Build UnitTest (IL2CPP) - uses: Cysharp/Actions/.github/actions/unity-builder@main - env: - UNITY_EMAIL: ${{ steps.op-load-secret.outputs.UNITY_EMAIL }} - UNITY_PASSWORD: ${{ steps.op-load-secret.outputs.UNITY_PASSWORD }} - UNITY_SERIAL: ${{ steps.op-load-secret.outputs.UNITY_SERIAL }} - with: - projectPath: src/MasterMemory.Unity - unityVersion: ${{ matrix.unity }} - targetPlatform: StandaloneLinux64 - buildMethod: UnitTestBuilder.BuildUnitTest - customParameters: "/headless /ScriptBackend IL2CPP" - - name: Check UnitTest file is generated - run: ls -lR ./src/MasterMemory.Unity/bin/UnitTest - - name: Execute UnitTest - run: ./src/MasterMemory.Unity/bin/UnitTest/StandaloneLinux64_IL2CPP/test - - # Store artifacts. - - uses: Cysharp/Actions/.github/actions/upload-artifact@main - with: - name: MasterMemory.${{ matrix.unity }}.unitypackage.zip - path: ./src/MasterMemory.Unity/*.unitypackage - retention-days: 1 + - run: dotnet test -c Debug --no-build \ No newline at end of file diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index cac196a..6ee5340 100644 --- a/.github/workflows/build-release.yml +++ b/.github/workflows/build-release.yml @@ -13,30 +13,15 @@ on: type: boolean jobs: - update-packagejson: - uses: Cysharp/Actions/.github/workflows/update-packagejson.yaml@main - with: - file-path: ./src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json - tag: ${{ inputs.tag }} - dry-run: ${{ inputs.dry-run }} - push-tag: false - build-dotnet: - needs: [update-packagejson] runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - with: - ref: ${{ needs.update-packagejson.outputs.sha }} - uses: Cysharp/Actions/.github/actions/setup-dotnet@main - with: - dotnet-version: | - 5.0.x - 6.0.x # pack nuget - run: dotnet build -c Release -p:Version=${{ inputs.tag }} - - run: dotnet test -c Release --no-build -p:Version=${{ inputs.tag }} + - run: dotnet test -c Release --no-build - run: dotnet pack -c Release --no-build -p:Version=${{ inputs.tag }} -o ./publish - uses: Cysharp/Actions/.github/actions/upload-artifact@main with: @@ -44,72 +29,13 @@ jobs: path: ./publish retention-days: 1 - build-unity: - needs: [update-packagejson] - strategy: - matrix: - unity: ["2022.3.39f1"] - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - name: Load secrets - id: op-load-secret - uses: 1password/load-secrets-action@v2 - with: - export-env: false - env: - OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN_PUBLIC }} - UNITY_EMAIL: "op://GitHubActionsPublic/UNITY_LICENSE/username" - UNITY_PASSWORD: "op://GitHubActionsPublic/UNITY_LICENSE/credential" - UNITY_SERIAL: "op://GitHubActionsPublic/UNITY_LICENSE/serial" - - - run: echo ${{ needs.update-packagejson.outputs.sha }} - - uses: actions/checkout@v4 - with: - ref: ${{ needs.update-packagejson.outputs.sha }} - - # Execute scripts: Export Package - # /opt/Unity/Editor/Unity -quit -batchmode -nographics -silent-crashes -logFile -projectPath . -executeMethod PackageExporter.Export - - name: Build Unity (.unitypacakge) - uses: Cysharp/Actions/.github/actions/unity-builder@main - env: - UNITY_EMAIL: ${{ steps.op-load-secret.outputs.UNITY_EMAIL }} - UNITY_PASSWORD: ${{ steps.op-load-secret.outputs.UNITY_PASSWORD }} - UNITY_SERIAL: ${{ steps.op-load-secret.outputs.UNITY_SERIAL }} - UNITY_PACKAGE_VERSION: ${{ inputs.tag }} - with: - projectPath: src/MasterMemory.Unity - unityVersion: ${{ matrix.unity }} - targetPlatform: StandaloneLinux64 - buildMethod: PackageExporter.Export - - - uses: Cysharp/Actions/.github/actions/check-metas@main # check meta files - with: - directory: src/MasterMemory.Unity - - # Store artifacts. - - uses: Cysharp/Actions/.github/actions/upload-artifact@main - with: - name: MasterMemory.Unity.${{ inputs.tag }}.unitypackage - path: ./src/MasterMemory.Unity/MasterMemory.Unity.${{ inputs.tag }}.unitypackage - retention-days: 1 - # release create-release: - needs: [update-packagejson, build-dotnet, build-unity] + needs: [build-dotnet] uses: Cysharp/Actions/.github/workflows/create-release.yaml@main with: - commit-id: ${{ needs.update-packagejson.outputs.sha }} + commit-id: ${{ github.sha }} dry-run: ${{ inputs.dry-run }} tag: ${{ inputs.tag }} nuget-push: true - release-upload: true - release-asset-path: ./MasterMemory.Unity.${{ inputs.tag }}.unitypackage/MasterMemory.Unity.${{ inputs.tag }}.unitypackage - secrets: inherit - - cleanup: - if: ${{ needs.update-packagejson.outputs.is-branch-created == 'true' }} - needs: [update-packagejson, build-unity] - uses: Cysharp/Actions/.github/workflows/clean-packagejson-branch.yaml@main - with: - branch: ${{ needs.update-packagejson.outputs.branch-name }} + secrets: inherit \ No newline at end of file diff --git a/MasterMemory.sln b/MasterMemory.sln index 510f348..f7489c6 100644 --- a/MasterMemory.sln +++ b/MasterMemory.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.28729.10 +# Visual Studio Version 17 +VisualStudioVersion = 17.12.35527.113 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{60662102-4523-441E-8D6C-D87A3246C648}" EndProject @@ -15,17 +15,17 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MasterMemory.Tests", "tests EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MasterMemory.Annotations", "src\MasterMemory.Annotations\MasterMemory.Annotations.csproj", "{A13F40DD-7777-4E97-9FC4-6324722CA964}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MasterMemory.GeneratorCore", "src\MasterMemory.GeneratorCore\MasterMemory.GeneratorCore.csproj", "{DAC2FED6-E960-4E57-949F-6B9185924E60}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MasterMemory.Generator", "src\MasterMemory.Generator\MasterMemory.Generator.csproj", "{625ECD09-F1E4-4979-B7A6-F94F23F7BBB0}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Benchmark", "sandbox\Benchmark\Benchmark.csproj", "{205509EA-78C8-4ED0-B2B5-8030DDFB0BF0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp", "sandbox\ConsoleApp\ConsoleApp.csproj", "{2657C9C5-0BEA-4616-BE41-A19E8298C591}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PerfTest2", "sandbox\PerfTest2\PerfTest2.csproj", "{AA5B5485-C42E-449C-843A-98A99A0D10B2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MasterMemory.MSBuild.Tasks", "src\MasterMemory.MSBuild.Tasks\MasterMemory.MSBuild.Tasks.csproj", "{433D4291-D2E3-4F36-8F2E-3E47F620DC9F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MasterMemory.SourceGenerator", "src\MasterMemory.SourceGenerator\MasterMemory.SourceGenerator.csproj", "{73F0ABAF-E55F-4E63-923B-4ABDE794D490}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GeneratorSandbox", "sandbox\GeneratorSandbox\GeneratorSandbox.csproj", "{D1D2B635-99CC-4C90-BAAB-57D188B5BE42}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MasterMemory.SourceGenerator.Tests", "tests\MasterMemory.SourceGenerator.Tests\MasterMemory.SourceGenerator.Tests.csproj", "{96F54302-35CD-4CDC-AAAC-8A6858DCAFEB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -45,14 +45,6 @@ Global {A13F40DD-7777-4E97-9FC4-6324722CA964}.Debug|Any CPU.Build.0 = Debug|Any CPU {A13F40DD-7777-4E97-9FC4-6324722CA964}.Release|Any CPU.ActiveCfg = Release|Any CPU {A13F40DD-7777-4E97-9FC4-6324722CA964}.Release|Any CPU.Build.0 = Release|Any CPU - {DAC2FED6-E960-4E57-949F-6B9185924E60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DAC2FED6-E960-4E57-949F-6B9185924E60}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DAC2FED6-E960-4E57-949F-6B9185924E60}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DAC2FED6-E960-4E57-949F-6B9185924E60}.Release|Any CPU.Build.0 = Release|Any CPU - {625ECD09-F1E4-4979-B7A6-F94F23F7BBB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {625ECD09-F1E4-4979-B7A6-F94F23F7BBB0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {625ECD09-F1E4-4979-B7A6-F94F23F7BBB0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {625ECD09-F1E4-4979-B7A6-F94F23F7BBB0}.Release|Any CPU.Build.0 = Release|Any CPU {205509EA-78C8-4ED0-B2B5-8030DDFB0BF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {205509EA-78C8-4ED0-B2B5-8030DDFB0BF0}.Debug|Any CPU.Build.0 = Debug|Any CPU {205509EA-78C8-4ED0-B2B5-8030DDFB0BF0}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -65,10 +57,18 @@ Global {AA5B5485-C42E-449C-843A-98A99A0D10B2}.Debug|Any CPU.Build.0 = Debug|Any CPU {AA5B5485-C42E-449C-843A-98A99A0D10B2}.Release|Any CPU.ActiveCfg = Release|Any CPU {AA5B5485-C42E-449C-843A-98A99A0D10B2}.Release|Any CPU.Build.0 = Release|Any CPU - {433D4291-D2E3-4F36-8F2E-3E47F620DC9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {433D4291-D2E3-4F36-8F2E-3E47F620DC9F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {433D4291-D2E3-4F36-8F2E-3E47F620DC9F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {433D4291-D2E3-4F36-8F2E-3E47F620DC9F}.Release|Any CPU.Build.0 = Release|Any CPU + {73F0ABAF-E55F-4E63-923B-4ABDE794D490}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {73F0ABAF-E55F-4E63-923B-4ABDE794D490}.Debug|Any CPU.Build.0 = Debug|Any CPU + {73F0ABAF-E55F-4E63-923B-4ABDE794D490}.Release|Any CPU.ActiveCfg = Release|Any CPU + {73F0ABAF-E55F-4E63-923B-4ABDE794D490}.Release|Any CPU.Build.0 = Release|Any CPU + {D1D2B635-99CC-4C90-BAAB-57D188B5BE42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1D2B635-99CC-4C90-BAAB-57D188B5BE42}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1D2B635-99CC-4C90-BAAB-57D188B5BE42}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1D2B635-99CC-4C90-BAAB-57D188B5BE42}.Release|Any CPU.Build.0 = Release|Any CPU + {96F54302-35CD-4CDC-AAAC-8A6858DCAFEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {96F54302-35CD-4CDC-AAAC-8A6858DCAFEB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {96F54302-35CD-4CDC-AAAC-8A6858DCAFEB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {96F54302-35CD-4CDC-AAAC-8A6858DCAFEB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -77,12 +77,12 @@ Global {D2720BBB-C233-4A1E-9768-1F00C9602180} = {60662102-4523-441E-8D6C-D87A3246C648} {8C5EBACA-C6C7-463B-B85C-C6A05E5DEB9F} = {BDAFF1CB-8E53-412B-B389-42A15343C7A3} {A13F40DD-7777-4E97-9FC4-6324722CA964} = {60662102-4523-441E-8D6C-D87A3246C648} - {DAC2FED6-E960-4E57-949F-6B9185924E60} = {60662102-4523-441E-8D6C-D87A3246C648} - {625ECD09-F1E4-4979-B7A6-F94F23F7BBB0} = {60662102-4523-441E-8D6C-D87A3246C648} {205509EA-78C8-4ED0-B2B5-8030DDFB0BF0} = {FFAA235C-D30F-4958-BC4E-60CD08979464} {2657C9C5-0BEA-4616-BE41-A19E8298C591} = {FFAA235C-D30F-4958-BC4E-60CD08979464} {AA5B5485-C42E-449C-843A-98A99A0D10B2} = {FFAA235C-D30F-4958-BC4E-60CD08979464} - {433D4291-D2E3-4F36-8F2E-3E47F620DC9F} = {60662102-4523-441E-8D6C-D87A3246C648} + {73F0ABAF-E55F-4E63-923B-4ABDE794D490} = {60662102-4523-441E-8D6C-D87A3246C648} + {D1D2B635-99CC-4C90-BAAB-57D188B5BE42} = {FFAA235C-D30F-4958-BC4E-60CD08979464} + {96F54302-35CD-4CDC-AAAC-8A6858DCAFEB} = {BDAFF1CB-8E53-412B-B389-42A15343C7A3} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {0121A3C4-6AE0-4622-BE04-05D9A3E729AC} diff --git a/README.md b/README.md index b6674b3..ecc3a46 100644 --- a/README.md +++ b/README.md @@ -2,30 +2,37 @@ MasterMemory === - -Embedded Typed Readonly In-Memory Document Database for .NET Core and Unity. +Source Generator based Embedded Typed Readonly In-Memory Document Database for .NET and Unity. ![image](https://user-images.githubusercontent.com/46207/61031896-61890800-a3fb-11e9-86b7-84c821d347a4.png) **4700** times faster than SQLite and achieves zero allocation per query. Also the DB size is small. When SQLite is 3560kb then MasterMemory is only 222kb. +Source Generator automatically generates a typed database structure from schemas (classes), which ensures that all queries are type-safe with full autocompletion support. + +![image](https://github.com/user-attachments/assets/e804fa52-f6a5-4972-a510-0b3b17a31230) + +![image](https://user-images.githubusercontent.com/46207/61035808-cb58e000-a402-11e9-9209-d51665d1cd56.png) + +This ensures both optimal performance and excellent usability. + ## Table of Contents - [Concept](#concept) -- [Getting Started(.NET Core)](#getting-startednet-core) +- [Getting Started(.NET)](#getting-startednet) - [Getting Started(Unity)](#getting-startedunity) - [DataTable configuration](#datatable-configuration) - [MemoryDatabase/RangeView](#memorydatabaserangeview) - [Extend Table](#extend-table) - [ImmutableBuilder](#immutablebuilder) -- [Immutable Data](#immutable-data) - [Validator](#validator) - [Metadata](#metadata) - [Inheritance](#inheritance) - [Optimization](#optimization) -- [Code Generator](#code-generator) +- [MasterMemoryGeneratorOptions](#mastermemorygeneratoroptions) +- [v2 -> v3 migration](#v2---v3-migration) - [License](#license) @@ -35,21 +42,19 @@ Concept * **Memory Efficient**, Only use underlying data memory and do aggressively string interning. * **Performance**, Similar as dictionary lookup. -* **TypeSafe**, 100% Type safe by pre code-generation. +* **TypeSafe**, 100% Type safe by Source Generator. * **Fast load speed**, MasterMemory save data by [MessagePack for C#, a fastest C# serializer](https://github.com/neuecc/MessagePack-CSharp) so load speed is blazing fast. * **Flexible Search**, Supports multiple key, multiple result, range/closest query. * **Validator**, You can define custom data validation by C#. * **Metadata**, To make custom importer/exporter, get the all database metadata. -These features are suitable for master data management(write-once, read-heavy) on embedded application such as role-playing game. MasterMemory has better performance than any other database solutions. [PalDB](https://github.com/linkedin/PalDB) developed by LinkedIn has a similar concept(embeddable write-once key-value store), but the implementation and performance characteristics are completely different. +These features are suitable for master data management(write-once, read-heavy) on embedded application, data analysis, game, etc. MasterMemory has better performance than any other database solutions. [PalDB](https://github.com/linkedin/PalDB) developed by LinkedIn has a similar concept(embeddable write-once key-value store), but the implementation and performance characteristics are completely different. -Getting Started(.NET Core) +Getting Started(.NET) --- -MasterMemory uses C# to C# code-generator. Runtime library API is the same but how to code-generate has different way between .NET Core and Unity. This sample is for .NET Core(for Unity is in below sections). - -Install the core library(Runtime and [Annotations](https://www.nuget.org/packages/MasterMemory.Annotations)). +Install the library(Runtime, Source Generator(Analyzer) and [Annotations](https://www.nuget.org/packages/MasterMemory.Annotations)) via NuGet. -> PM> Install-Package [MasterMemory](https://www.nuget.org/packages/MasterMemory) +> dotnet add package [MasterMemory](https://www.nuget.org/packages/MasterMemory) Prepare the example table definition like following. @@ -62,62 +67,50 @@ public enum Gender // table definition marked by MemoryTableAttribute. // database-table must be serializable by MessagePack-CSsharp [MemoryTable("person"), MessagePackObject(true)] -public class Person +public record Person { // index definition by attributes. [PrimaryKey] - public int PersonId { get; set; } + public required int PersonId { get; init; } // secondary index can add multiple(discriminated by index-number). [SecondaryKey(0), NonUnique] [SecondaryKey(1, keyOrder: 1), NonUnique] - public int Age { get; set; } + public required int Age { get; init; } [SecondaryKey(2), NonUnique] [SecondaryKey(1, keyOrder: 0), NonUnique] - public Gender Gender { get; set; } + public required Gender Gender { get; init; } - public string Name { get; set; } + public required string Name { get; init; } } ``` -Edit the `.csproj`, add [MasterMemory.MSBuild.Tasks](https://www.nuget.org/packages/MasterMemory.MSBuild.Tasks) and add configuration like following. - -```xml - - - - - - - - - - - -``` +Data in MasterMemory is readonly, so it is recommended to use an immutable structure. While both records and classes are supported, records might be preferable as they generate more readable ToString methods. -After the build, generated files(`DatabaseBuilder.cs`, `ImmutableBuilder.cs`, `MasterMemoryResolver.cs`, `MemoryDatabase.cs` and `Tables/***Table.cs`) in OutputDirectory. +MasterMemory's Source Generator detects types marked with the `MemoryTable` attribute and automatically generates types like the following: -![image](https://user-images.githubusercontent.com/46207/61233535-ba460100-a76b-11e9-85d0-c34cb5ce7482.png) +![image](https://github.com/user-attachments/assets/e804fa52-f6a5-4972-a510-0b3b17a31230) Finally, you can regsiter and query by these files. ```csharp +using ...; // Your project default namespace + // to create database, use DatabaseBuilder and Append method. var builder = new DatabaseBuilder(); builder.Append(new Person[] { - new Person { PersonId = 0, Age = 13, Gender = Gender.Male, Name = "Dana Terry" }, - new Person { PersonId = 1, Age = 17, Gender = Gender.Male, Name = "Kirk Obrien" }, - new Person { PersonId = 2, Age = 31, Gender = Gender.Male, Name = "Wm Banks" }, - new Person { PersonId = 3, Age = 44, Gender = Gender.Male, Name = "Karl Benson" }, - new Person { PersonId = 4, Age = 23, Gender = Gender.Male, Name = "Jared Holland" }, - new Person { PersonId = 5, Age = 27, Gender = Gender.Female, Name = "Jeanne Phelps" }, - new Person { PersonId = 6, Age = 25, Gender = Gender.Female, Name = "Willie Rose" }, - new Person { PersonId = 7, Age = 11, Gender = Gender.Female, Name = "Shari Gutierrez" }, - new Person { PersonId = 8, Age = 63, Gender = Gender.Female, Name = "Lori Wilson" }, - new Person { PersonId = 9, Age = 34, Gender = Gender.Female, Name = "Lena Ramsey" }, + new (){ PersonId = 0, Age = 13, Gender = Gender.Male, Name = "Dana Terry" }, + new (){ PersonId = 1, Age = 17, Gender = Gender.Male, Name = "Kirk Obrien" }, + new (){ PersonId = 2, Age = 31, Gender = Gender.Male, Name = "Wm Banks" }, + new (){ PersonId = 3, Age = 44, Gender = Gender.Male, Name = "Karl Benson" }, + new (){ PersonId = 4, Age = 23, Gender = Gender.Male, Name = "Jared Holland" }, + new (){ PersonId = 5, Age = 27, Gender = Gender.Female, Name = "Jeanne Phelps" }, + new (){ PersonId = 6, Age = 25, Gender = Gender.Female, Name = "Willie Rose" }, + new (){ PersonId = 7, Age = 11, Gender = Gender.Female, Name = "Shari Gutierrez" }, + new (){ PersonId = 8, Age = 63, Gender = Gender.Female, Name = "Lori Wilson" }, + new (){ PersonId = 9, Age = 34, Gender = Gender.Female, Name = "Lena Ramsey" }, }); // build database binary(you can also use `WriteToStream` for save to file). @@ -130,7 +123,7 @@ byte[] data = builder.Build(); var db = new MemoryDatabase(data); // .PersonTable.FindByPersonId is fully typed by code-generation. -Person person = db.PersonTable.FindByPersonId(10); +Person person = db.PersonTable.FindByPersonId(5); // Multiple key is also typed(***And * **), Return value is multiple if key is marked with `NonUnique`. RangeView result = db.PersonTable.FindByGenderAndAge((Gender.Female, 23)); @@ -150,9 +143,26 @@ You can invoke all indexed query by IntelliSense. Getting Started(Unity) --- -Check the [releases](https://github.com/Cysharp/MasterMemory/releases) page, download `MasterMemory.Unity.unitypackage`(runtime) and `MasterMemory.Generator.zip`(cli code-generator). MasterMemory also depends on MessagePack-CSharp so you have to download `MessagePack.Unity.2.*.*.unitypackage` and `mpc.zip` from [MessagePack-CSharp/releases page](https://github.com/neuecc/MessagePack-CSharp/releases). +The minimum supported Unity version will be `2022.3.12f1`, as it is necessary to support C# Incremental Source Generator(Compiler Version, 4.3.0). -Prepare the example table definition like following. +Since this library is provided via NuGet, install [NuGetForUnity](https://github.com/GlitchEnzo/NuGetForUnity), then navigate to Open Window from NuGet -> Manage NuGet Packages, Search "MasterMemory" and Press Install. + +First, it is recommended to define assembly attributes in any cs file to enable the use of `init`. + +```csharp +// Optional: Unity can't load default namespace to Source Generator +// If not specified, 'MasterMemory' will be used by default, +// but you can use this attribute if you want to specify a different namespace. +[assembly: MasterMemoryGeneratorOptions(Namespace = "MyProj")] + +// Optional: If you want to use init keyword, copy-and-paste this. +namespace System.Runtime.CompilerServices +{ + internal sealed class IsExternalInit { } +} +``` + +Everything else is the same as the standard .NET version. While the `required` keyword can't be used since it's from C# 11, using `init` alone is sufficient to guarantee immutability. ```csharp public enum Gender @@ -163,46 +173,26 @@ public enum Gender // table definition marked by MemoryTableAttribute. // database-table must be serializable by MessagePack-CSsharp [MemoryTable("person"), MessagePackObject(true)] -public class Person +public record Person { // index definition by attributes. [PrimaryKey] - public int PersonId { get; set; } + public int PersonId { get; init; } // secondary index can add multiple(discriminated by index-number). [SecondaryKey(0), NonUnique] [SecondaryKey(1, keyOrder: 1), NonUnique] - public int Age { get; set; } + public int Age { get; init; } [SecondaryKey(2), NonUnique] [SecondaryKey(1, keyOrder: 0), NonUnique] - public Gender Gender { get; set; } + public Gender Gender { get; init; } - public string Name { get; set; } + public string Name { get; init; } } ``` -use the MasterMemory code generator by commandline. Commandline tool support platforms are `win-x64`, `osx-x64` and `linux-x64`. - -``` -Usage: MasterMemory.Generator [options...] - -Options: - -i, -inputDirectory Input file directory(search recursive). (Required) - -o, -outputDirectory Output file directory. (Required) - -n, -usingNamespace Namespace of generated files. (Required) - -p, -prefixClassName Prefix of class names. (Default: ) - -c, -addImmutableConstructor Add immutable constructor to MemoryTable class. (Default: False) - -t, -returnNullIfKeyNotFound Return null if key not found on unique find method. (Default: False) -``` - -```bash -MasterMemory.Generator.exe -i "C:\UnitySample" -o "C:\UnitySample\Generated" -n "UnitySample" -``` - -Also you need to generated MessagePack-CSharp code generation. - -Additional steps, you have to set up to use generated resolver. +Also, for use with IL2CPP, you need to add the generated `MasterMemoryResolver` to MessagePack's Resolver. If you need other generated Resolvers, such as those from [MagicOnion](https://github.com/Cysharp/MagicOnion), please add and compose them here. ```csharp public static class Initializer @@ -210,65 +200,21 @@ public static class Initializer [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] public static void SetupMessagePackResolver() { + // Create CompositeResolver StaticCompositeResolver.Instance.Register(new[]{ MasterMemoryResolver.Instance, // set MasterMemory generated resolver - GeneratedResolver.Instance, // set MessagePack generated resolver StandardResolver.Instance // set default MessagePack resolver }); + // Create options with resolver var options = MessagePackSerializerOptions.Standard.WithResolver(StaticCompositeResolver.Instance); + + // Optional: as default. MessagePackSerializer.DefaultOptions = options; } } ``` -The rest is the same as .NET Core version. - -```csharp -// to create database, use DatabaseBuilder and Append method. -var builder = new DatabaseBuilder(); -builder.Append(new Person[] -{ - new Person { PersonId = 0, Age = 13, Gender = Gender.Male, Name = "Dana Terry" }, - new Person { PersonId = 1, Age = 17, Gender = Gender.Male, Name = "Kirk Obrien" }, - new Person { PersonId = 2, Age = 31, Gender = Gender.Male, Name = "Wm Banks" }, - new Person { PersonId = 3, Age = 44, Gender = Gender.Male, Name = "Karl Benson" }, - new Person { PersonId = 4, Age = 23, Gender = Gender.Male, Name = "Jared Holland" }, - new Person { PersonId = 5, Age = 27, Gender = Gender.Female, Name = "Jeanne Phelps" }, - new Person { PersonId = 6, Age = 25, Gender = Gender.Female, Name = "Willie Rose" }, - new Person { PersonId = 7, Age = 11, Gender = Gender.Female, Name = "Shari Gutierrez" }, - new Person { PersonId = 8, Age = 63, Gender = Gender.Female, Name = "Lori Wilson" }, - new Person { PersonId = 9, Age = 34, Gender = Gender.Female, Name = "Lena Ramsey" }, -}); - -// build database binary(you can also use `WriteToStream` for save to file). -byte[] data = builder.Build(); - -// ----------------------- - -// for query phase, create MemoryDatabase. -// (MemoryDatabase is recommended to store in singleton container(static field/DI)). -var db = new MemoryDatabase(data); - -// .PersonTable.FindByPersonId is fully typed by code-generation. -Person person = db.PersonTable.FindByPersonId(10); - -// Multiple key is also typed(***And * **), Return value is multiple if key is marked with `NonUnique`. -RangeView result = db.PersonTable.FindByGenderAndAge((Gender.Female, 23)); - -// Get nearest value(choose lower(default) or higher). -RangeView age1 = db.PersonTable.FindClosestByAge(31); - -// Get range(min-max inclusive). -RangeView age2 = db.PersonTable.FindRangeByAge(20, 29); -``` - -All table(marked by `MemoryTableAttribute`) and methods(created by `PrimaryKeyAttribute` or `SecondaryKeyAttribute`) are typed. - -![image](https://user-images.githubusercontent.com/46207/61035808-cb58e000-a402-11e9-9209-d51665d1cd56.png) - -You can invoke all indexed query by IntelliSense. - DataTable configuration --- Element type of datatable must be marked by `[MemoryTable(tableName)]`, datatable is generated from marked type. `string tableName` is saved in database binary, you can rename class name if tableName is same. @@ -473,48 +419,6 @@ public class GameRoom } ``` -Immutable Data ---- -Element data is shared in the application so ideally should be immutable. But C# only has a constructor to create immutable data, it is too difficult to create many data tables. - -Code generator has `AddImmutableConstructor`(`-c, -addImmutableConstructor`) option. If enabled it, code generator modify orignal file and add immutable constructor in target type. If you define property as `{get; private set;}` or `{get;}`, it will be immutable type. - -```csharp -// For the versioning, MessagePackObject is recommended to use string key. -[MemoryTable("person"), MessagePackObject(true)] -public class Person -{ - [PrimaryKey] - public int PersonId { get; } - public int Age { get; } - public Gender Gender { get; } - public string Name { get; } -} - -// use AddImmutableConstructor="true" or -c option - -MasterMemory.Generator.exe -i "C:\UnitySample" -o "C:\UnitySample\Generated" -n "UnitySample" -c - -// after generated... -[MemoryTable("person"), MessagePackObject(true)] -public class Person -{ - [PrimaryKey] - public int PersonId { get; } - public int Age { get; } - public Gender Gender { get; } - public string Name { get; } - - public Person(int PersonId, int Age, Gender Gender, string Name) - { - this.PersonId = PersonId; - this.Age = Age; - this.Gender = Gender; - this.Name = Name; - } -} -``` - Validator --- You can validate data by `MemoryDatabase.Validate` method. In default, it check unique key(data duplicated) and you can define custom validate logics. @@ -642,58 +546,54 @@ If creates console-app, our [ConsoleAppFramework](https://github.com/Cysharp/Con Here is sample of reading and creating dynamic from csv. `builder.AppendDynamic` and `System.Runtime.Serialization.FormatterServices.GetUninitializedObject` will help it. ```csharp -class Program -{ - static void Main(string[] args) - { - var csv = @"monster_id,name,max_hp +var csv = @"monster_id,name,max_hp 1,foo,100 2,bar,200"; - var fileName = "monster"; +var fileName = "monster"; - var builder = new DatabaseBuilder(); +var builder = new DatabaseBuilder(); + +var meta = MemoryDatabase.GetMetaDatabase(); +var table = meta.GetTableInfo(fileName); - var meta = MemoryDatabase.GetMetaDatabase(); - var table = meta.GetTableInfo(fileName); +var tableData = new List(); - var tableData = new List(); +using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(csv))) +using (var sr = new StreamReader(ms, Encoding.UTF8)) +using (var reader = new TinyCsvReader(sr)) +{ + while ((reader.ReadValuesWithHeader() is Dictionary values)) + { + // create data without call constructor + // use System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject instead on .NET 8 + var data = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(table.DataType); - using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(csv))) - using (var sr = new StreamReader(ms, Encoding.UTF8)) - using (var reader = new TinyCsvReader(sr)) + foreach (var prop in table.Properties) { - while ((reader.ReadValuesWithHeader() is Dictionary values)) + if (values.TryGetValue(prop.NameSnakeCase, out var rawValue)) { - // create data without call constructor - var data = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(table.DataType); - - foreach (var prop in table.Properties) + var value = ParseValue(prop.PropertyInfo.PropertyType, rawValue); + if (prop.PropertyInfo.SetMethod == null) { - if (values.TryGetValue(prop.NameSnakeCase, out var rawValue)) - { - var value = ParseValue(prop.PropertyInfo.PropertyType, rawValue); - if (prop.PropertyInfo.SetMethod == null) - { - throw new Exception("Target property does not exists set method. If you use {get;}, please change to { get; private set; }, Type:" + prop.PropertyInfo.DeclaringType + " Prop:" + prop.PropertyInfo.Name); - } - prop.PropertyInfo.SetValue(data, value); - } - else - { - throw new KeyNotFoundException($"Not found \"{prop.NameSnakeCase}\" in \"{fileName}.csv\" header."); - } + throw new Exception("Target property does not exists set method. If you use {get;}, please change to { get; private set; }, Type:" + prop.PropertyInfo.DeclaringType + " Prop:" + prop.PropertyInfo.Name); } - - tableData.Add(data); + prop.PropertyInfo.SetValue(data, value); + } + else + { + throw new KeyNotFoundException($"Not found \"{prop.NameSnakeCase}\" in \"{fileName}.csv\" header."); } } - // add dynamic collection. - builder.AppendDynamic(table.DataType, tableData); - - var bin = builder.Build(); - var database = new MemoryDatabase(bin); + tableData.Add(data); } +} + +// add dynamic collection. +builder.AppendDynamic(table.DataType, tableData); + +var bin = builder.Build(); +var database = new MemoryDatabase(bin); static object ParseValue(Type type, string rawValue) { @@ -896,59 +796,31 @@ The use of Parallel can greatly improve the construct performance. Recommend to If you want to reduce code size of generated code, Validator and MetaDatabase info can omit in runtime. Generated code has two symbols `DISABLE_MASTERMEMORY_VALIDATOR` and `DISABLE_MASTERMEMORY_METADATABASE`. By defining them, can be erased from the build code. -Code Generator +The database generation/loading speed and size are affected by MessagePack's serialization format. Using `[MessagePackObject]` with `[Key]` attributes instead of `[MessagePackObject(true)]` can improve loading speed and reduce size. However, regarding size, since LZ4 compression is used by default, the difference may not be significant. + +MasterMemoryGeneratorOptions --- -MasterMemory has two kinds of code-generator. `MSBuild Task`, `.NET Core Global/Local Tools`. - -MSBuild Task(`MasterMemory.MSBuild.Tasks`) is recommended way to use in .NET Core csproj. - -```xml - -``` +The Source Generator settings are configured using the assembly attribute `[MasterMemoryGeneratorOptions]`. By placing it in any file, you can configure the following settings. -`.NET Core Global/Local Tools` can install from NuGet(`MasterMemory.Generator`), you need to install .NET runtime. Here is the sample command of install global tool. +```csharp +[assembly: MasterMemoryGeneratorOptions( + Namespace = "MyConsoleApp", + IsReturnNullIfKeyNotFound = true, + PrefixClassName = "Foo" +)] +``` -`dotnet tool install --global MasterMemory.Generator` +* `Namespace`: Changes the namespace of generated files. If not specified, it tries to get the `RootNamespace` set in the csproj file; if that's not available, it defaults to `MasterMemory` +* `IsReturnNullIfKeyNotFound`: By default, the `Find` method throws a `KeyNotFoundException` when a key is not found. If set to true, the return type becomes `T?` and returns null instead +* `PrefixClassName`: Adds a prefix to the class names of generated files. For example, `DatabaseBuilder` becomes `FooDatabaseBuilder`. This allows you to distinguish between multiple MasterMemory projects by name. -``` -Usage: MasterMemory.Generator [options...] - -Options: - -i, -inputDirectory Input file directory(search recursive). (Required) - -o, -outputDirectory Output file directory. (Required) - -n, -usingNamespace Namespace of generated files. (Required) - -p, -prefixClassName Prefix of class names. (Default: ) - -c, -addImmutableConstructor Add immutable constructor to MemoryTable class. (Default: False) - -t, -returnNullIfKeyNotFound Return null if key not found on unique find method. (Default: False) -``` +v2 -> v3 migration +--- +Since there are no changes to the API, binary format, or behavior, you can migrate simply by changing the command-line tool settings to the assembly attribute `[MasterMemoryGeneratorOptions]`. -After install, you can call by `dotnet mmgen` command. This is useful to use in CI. Here is the sample of CircleCI config. - -```yml -version: 2.1 -executors: - dotnet: - docker: - - image: mcr.microsoft.com/dotnet/core/sdk:2.2 - environment: - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - NUGET_XMLDOC_MODE: skip -jobs: - gen-mastermemory: - executor: dotnet - steps: - - checkout - - run: dotnet tool install --global MasterMemory.Generator - - run: dotnet mmgen -i ./ -o ./MasterMemory -n Test - /* git push or store artifacts or etc...... */ -``` +* The code generator (MSBuild Task, .NET Core Global/Local Tools) has been removed and replaced with Source Generator +* Tool options are now available through `MasterMemoryGeneratorOptions` +* The `-addImmutableConstructor` option has been completely removed; please use C#'s record or init keyword instead License --- diff --git a/sandbox/Benchmark/Benchmark.csproj b/sandbox/Benchmark/Benchmark.csproj index 5c05096..623e4a7 100644 --- a/sandbox/Benchmark/Benchmark.csproj +++ b/sandbox/Benchmark/Benchmark.csproj @@ -1,28 +1,29 @@  - - Exe - net6.0 - false - + + Exe + net6.0 + false + 1701;1702;NU1904 + - - - - - - - - - + + + + + + + + + - - - - - - - - + + + + + Analyzer + false + + diff --git a/sandbox/Benchmark/Generated/DatabaseBuilder.cs b/sandbox/Benchmark/Generated/DatabaseBuilder.cs deleted file mode 100644 index 0daaf22..0000000 --- a/sandbox/Benchmark/Generated/DatabaseBuilder.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -using LiteDB; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using TestPerfLiteDB.Tables; - -namespace TestPerfLiteDB -{ - public sealed class DatabaseBuilder : DatabaseBuilderBase - { - public DatabaseBuilder() : this(null) { } - public DatabaseBuilder(MessagePack.IFormatterResolver resolver) : base(resolver) { } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.id, System.Collections.Generic.Comparer.Default); - return this; - } - - } -} \ No newline at end of file diff --git a/sandbox/Benchmark/Generated/ImmutableBuilder.cs b/sandbox/Benchmark/Generated/ImmutableBuilder.cs deleted file mode 100644 index 3f6c119..0000000 --- a/sandbox/Benchmark/Generated/ImmutableBuilder.cs +++ /dev/null @@ -1,64 +0,0 @@ -// -using LiteDB; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using TestPerfLiteDB.Tables; - -namespace TestPerfLiteDB -{ - public sealed class ImmutableBuilder : ImmutableBuilderBase - { - MemoryDatabase memory; - - public ImmutableBuilder(MemoryDatabase memory) - { - this.memory = memory; - } - - public MemoryDatabase Build() - { - return memory; - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.id, System.Collections.Generic.Comparer.Default); - var table = new TestDocTable(newData); - memory = new MemoryDatabase( - table - - ); - } - - public void RemoveTestDoc(int[] keys) - { - var data = RemoveCore(memory.TestDocTable.GetRawDataUnsafe(), keys, x => x.id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.id, System.Collections.Generic.Comparer.Default); - var table = new TestDocTable(newData); - memory = new MemoryDatabase( - table - - ); - } - - public void Diff(TestDoc[] addOrReplaceData) - { - var data = DiffCore(memory.TestDocTable.GetRawDataUnsafe(), addOrReplaceData, x => x.id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.id, System.Collections.Generic.Comparer.Default); - var table = new TestDocTable(newData); - memory = new MemoryDatabase( - table - - ); - } - - } -} \ No newline at end of file diff --git a/sandbox/Benchmark/Generated/MasterMemoryResolver.cs b/sandbox/Benchmark/Generated/MasterMemoryResolver.cs deleted file mode 100644 index a4fa015..0000000 --- a/sandbox/Benchmark/Generated/MasterMemoryResolver.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -using LiteDB; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using TestPerfLiteDB.Tables; - -namespace TestPerfLiteDB -{ - public class MasterMemoryResolver : global::MessagePack.IFormatterResolver - { - public static readonly global::MessagePack.IFormatterResolver Instance = new MasterMemoryResolver(); - - MasterMemoryResolver() - { - - } - - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() - { - return FormatterCache.formatter; - } - - static class FormatterCache - { - public static readonly global::MessagePack.Formatters.IMessagePackFormatter formatter; - - static FormatterCache() - { - var f = MasterMemoryResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (f != null) - { - formatter = (global::MessagePack.Formatters.IMessagePackFormatter)f; - } - } - } - } - - internal static class MasterMemoryResolverGetFormatterHelper - { - static readonly global::System.Collections.Generic.Dictionary lookup; - - static MasterMemoryResolverGetFormatterHelper() - { - lookup = new global::System.Collections.Generic.Dictionary(1) - { - {typeof(TestDoc[]), 0 }, - }; - } - - internal static object GetFormatter(Type t) - { - int key; - if (!lookup.TryGetValue(t, out key)) return null; - - switch (key) - { - case 0: return new MessagePack.Formatters.ArrayFormatter(); - default: return null; - } - } - } -} \ No newline at end of file diff --git a/sandbox/Benchmark/Generated/MemoryDatabase.cs b/sandbox/Benchmark/Generated/MemoryDatabase.cs deleted file mode 100644 index 9c46364..0000000 --- a/sandbox/Benchmark/Generated/MemoryDatabase.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -using LiteDB; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using TestPerfLiteDB.Tables; -using MasterMemory.Validation; - -namespace TestPerfLiteDB -{ - public sealed class MemoryDatabase : MemoryDatabaseBase - { - public TestDocTable TestDocTable { get; private set; } - - public MemoryDatabase( - TestDocTable TestDocTable - ) - { - this.TestDocTable = TestDocTable; - } - - public MemoryDatabase(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) - : base(databaseBinary, internString, formatterResolver, maxDegreeOfParallelism) - { - } - - protected override void Init(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - this.TestDocTable = ExtractTableData(header, databaseBinary, options, xs => new TestDocTable(xs)); - } - - public ImmutableBuilder ToImmutableBuilder() - { - return new ImmutableBuilder(this); - } - - public DatabaseBuilder ToDatabaseBuilder() - { - var builder = new DatabaseBuilder(); - builder.Append(this.TestDocTable.GetRawDataUnsafe()); - return builder; - } - - public ValidateResult Validate() - { - var result = new ValidateResult(); - var database = new ValidationDatabase(new object[] - { - TestDocTable, - }); - - // ValidateTable(TestDocTable.All, database, result); - - return result; - } - } -} \ No newline at end of file diff --git a/sandbox/Benchmark/Generated/Tables/TestDocTable.cs b/sandbox/Benchmark/Generated/Tables/TestDocTable.cs deleted file mode 100644 index 8686a2e..0000000 --- a/sandbox/Benchmark/Generated/Tables/TestDocTable.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -using LiteDB; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; - -namespace TestPerfLiteDB.Tables -{ - public sealed partial class TestDocTable : TableBase - { - readonly Func primaryIndexSelector; - - - public TestDocTable(TestDoc[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.id; - } - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public TestDoc FindByid(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return default; - } - - public TestDoc FindClosestByid(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByid(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/ConsoleApp.csproj b/sandbox/ConsoleApp/ConsoleApp.csproj index bddb857..3ebaf3a 100644 --- a/sandbox/ConsoleApp/ConsoleApp.csproj +++ b/sandbox/ConsoleApp/ConsoleApp.csproj @@ -1,26 +1,26 @@ - - Exe - net6.0 - false - + + Exe + net9.0 + false + - - $(DefineConstants)TRACE; - + + $(DefineConstants)TRACE; + - - $(DefineConstants)TRACE; - + + $(DefineConstants)TRACE; + - - - - - - - - + + + + + Analyzer + false + + diff --git a/sandbox/ConsoleApp/Generated/DatabaseBuilder.cs b/sandbox/ConsoleApp/Generated/DatabaseBuilder.cs deleted file mode 100644 index f70fb7b..0000000 --- a/sandbox/ConsoleApp/Generated/DatabaseBuilder.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; -using ConsoleApp.Tables; - -namespace ConsoleApp -{ - public sealed class DatabaseBuilder : DatabaseBuilderBase - { - public DatabaseBuilder() : this(null) { } - public DatabaseBuilder(MessagePack.IFormatterResolver resolver) : base(resolver) { } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Gender, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.ItemId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.MonsterId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.PersonId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/ImmutableBuilder.cs b/sandbox/ConsoleApp/Generated/ImmutableBuilder.cs deleted file mode 100644 index 5034d16..0000000 --- a/sandbox/ConsoleApp/Generated/ImmutableBuilder.cs +++ /dev/null @@ -1,387 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; -using ConsoleApp.Tables; - -namespace ConsoleApp -{ - public sealed class ImmutableBuilder : ImmutableBuilderBase - { - MemoryDatabase memory; - - public ImmutableBuilder(MemoryDatabase memory) - { - this.memory = memory; - } - - public MemoryDatabase Build() - { - return memory; - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Gender, System.Collections.Generic.Comparer.Default); - var table = new EnumKeyTableTable(newData); - memory = new MemoryDatabase( - table, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void RemoveEnumKeyTable(Gender[] keys) - { - var data = RemoveCore(memory.EnumKeyTableTable.GetRawDataUnsafe(), keys, x => x.Gender, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Gender, System.Collections.Generic.Comparer.Default); - var table = new EnumKeyTableTable(newData); - memory = new MemoryDatabase( - table, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void Diff(EnumKeyTable[] addOrReplaceData) - { - var data = DiffCore(memory.EnumKeyTableTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Gender, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Gender, System.Collections.Generic.Comparer.Default); - var table = new EnumKeyTableTable(newData); - memory = new MemoryDatabase( - table, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - table, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void RemoveItem(int[] keys) - { - var data = RemoveCore(memory.ItemTable.GetRawDataUnsafe(), keys, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - table, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void Diff(Item[] addOrReplaceData) - { - var data = DiffCore(memory.ItemTable.GetRawDataUnsafe(), addOrReplaceData, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - table, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.MonsterId, System.Collections.Generic.Comparer.Default); - var table = new MonsterTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - table, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void RemoveMonster(int[] keys) - { - var data = RemoveCore(memory.MonsterTable.GetRawDataUnsafe(), keys, x => x.MonsterId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.MonsterId, System.Collections.Generic.Comparer.Default); - var table = new MonsterTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - table, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void Diff(Monster[] addOrReplaceData) - { - var data = DiffCore(memory.MonsterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.MonsterId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.MonsterId, System.Collections.Generic.Comparer.Default); - var table = new MonsterTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - table, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.PersonId, System.Collections.Generic.Comparer.Default); - var table = new PersonTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - table, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void RemovePerson(int[] keys) - { - var data = RemoveCore(memory.PersonTable.GetRawDataUnsafe(), keys, x => x.PersonId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.PersonId, System.Collections.Generic.Comparer.Default); - var table = new PersonTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - table, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void Diff(Person[] addOrReplaceData) - { - var data = DiffCore(memory.PersonTable.GetRawDataUnsafe(), addOrReplaceData, x => x.PersonId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.PersonId, System.Collections.Generic.Comparer.Default); - var table = new PersonTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - table, - memory.QuestTable, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new QuestTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - table, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void RemoveQuest(int[] keys) - { - var data = RemoveCore(memory.QuestTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new QuestTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - table, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void Diff(Quest[] addOrReplaceData) - { - var data = DiffCore(memory.QuestTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new QuestTable(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - table, - memory.Test1Table, - memory.Test2Table - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new Test1Table(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - table, - memory.Test2Table - - ); - } - - public void RemoveTest1(int[] keys) - { - var data = RemoveCore(memory.Test1Table.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new Test1Table(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - table, - memory.Test2Table - - ); - } - - public void Diff(Test1[] addOrReplaceData) - { - var data = DiffCore(memory.Test1Table.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new Test1Table(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - table, - memory.Test2Table - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new Test2Table(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - table - - ); - } - - public void RemoveTest2(int[] keys) - { - var data = RemoveCore(memory.Test2Table.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new Test2Table(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - table - - ); - } - - public void Diff(Test2[] addOrReplaceData) - { - var data = DiffCore(memory.Test2Table.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new Test2Table(newData); - memory = new MemoryDatabase( - memory.EnumKeyTableTable, - memory.ItemTable, - memory.MonsterTable, - memory.PersonTable, - memory.QuestTable, - memory.Test1Table, - table - - ); - } - - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/MasterMemoryResolver.cs b/sandbox/ConsoleApp/Generated/MasterMemoryResolver.cs deleted file mode 100644 index 654d66c..0000000 --- a/sandbox/ConsoleApp/Generated/MasterMemoryResolver.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; -using ConsoleApp.Tables; - -namespace ConsoleApp -{ - public class MasterMemoryResolver : global::MessagePack.IFormatterResolver - { - public static readonly global::MessagePack.IFormatterResolver Instance = new MasterMemoryResolver(); - - MasterMemoryResolver() - { - - } - - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() - { - return FormatterCache.formatter; - } - - static class FormatterCache - { - public static readonly global::MessagePack.Formatters.IMessagePackFormatter formatter; - - static FormatterCache() - { - var f = MasterMemoryResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (f != null) - { - formatter = (global::MessagePack.Formatters.IMessagePackFormatter)f; - } - } - } - } - - internal static class MasterMemoryResolverGetFormatterHelper - { - static readonly global::System.Collections.Generic.Dictionary lookup; - - static MasterMemoryResolverGetFormatterHelper() - { - lookup = new global::System.Collections.Generic.Dictionary(7) - { - {typeof(EnumKeyTable[]), 0 }, - {typeof(Item[]), 1 }, - {typeof(Monster[]), 2 }, - {typeof(Person[]), 3 }, - {typeof(Quest[]), 4 }, - {typeof(Test1[]), 5 }, - {typeof(Test2[]), 6 }, - }; - } - - internal static object GetFormatter(Type t) - { - int key; - if (!lookup.TryGetValue(t, out key)) return null; - - switch (key) - { - case 0: return new MessagePack.Formatters.ArrayFormatter(); - case 1: return new MessagePack.Formatters.ArrayFormatter(); - case 2: return new MessagePack.Formatters.ArrayFormatter(); - case 3: return new MessagePack.Formatters.ArrayFormatter(); - case 4: return new MessagePack.Formatters.ArrayFormatter(); - case 5: return new MessagePack.Formatters.ArrayFormatter(); - case 6: return new MessagePack.Formatters.ArrayFormatter(); - default: return null; - } - } - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/MemoryDatabase.cs b/sandbox/ConsoleApp/Generated/MemoryDatabase.cs deleted file mode 100644 index 2c2ac9f..0000000 --- a/sandbox/ConsoleApp/Generated/MemoryDatabase.cs +++ /dev/null @@ -1,212 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; -using ConsoleApp.Tables; - -namespace ConsoleApp -{ - public sealed class MemoryDatabase : MemoryDatabaseBase - { - public EnumKeyTableTable EnumKeyTableTable { get; private set; } - public ItemTable ItemTable { get; private set; } - public MonsterTable MonsterTable { get; private set; } - public PersonTable PersonTable { get; private set; } - public QuestTable QuestTable { get; private set; } - public Test1Table Test1Table { get; private set; } - public Test2Table Test2Table { get; private set; } - - public MemoryDatabase( - EnumKeyTableTable EnumKeyTableTable, - ItemTable ItemTable, - MonsterTable MonsterTable, - PersonTable PersonTable, - QuestTable QuestTable, - Test1Table Test1Table, - Test2Table Test2Table - ) - { - this.EnumKeyTableTable = EnumKeyTableTable; - this.ItemTable = ItemTable; - this.MonsterTable = MonsterTable; - this.PersonTable = PersonTable; - this.QuestTable = QuestTable; - this.Test1Table = Test1Table; - this.Test2Table = Test2Table; - } - - public MemoryDatabase(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) - : base(databaseBinary, internString, formatterResolver, maxDegreeOfParallelism) - { - } - - protected override void Init(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - if(maxDegreeOfParallelism == 1) - { - InitSequential(header, databaseBinary, options, maxDegreeOfParallelism); - } - else - { - InitParallel(header, databaseBinary, options, maxDegreeOfParallelism); - } - } - - void InitSequential(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - this.EnumKeyTableTable = ExtractTableData(header, databaseBinary, options, xs => new EnumKeyTableTable(xs)); - this.ItemTable = ExtractTableData(header, databaseBinary, options, xs => new ItemTable(xs)); - this.MonsterTable = ExtractTableData(header, databaseBinary, options, xs => new MonsterTable(xs)); - this.PersonTable = ExtractTableData(header, databaseBinary, options, xs => new PersonTable(xs)); - this.QuestTable = ExtractTableData(header, databaseBinary, options, xs => new QuestTable(xs)); - this.Test1Table = ExtractTableData(header, databaseBinary, options, xs => new Test1Table(xs)); - this.Test2Table = ExtractTableData(header, databaseBinary, options, xs => new Test2Table(xs)); - } - - void InitParallel(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - var extracts = new Action[] - { - () => this.EnumKeyTableTable = ExtractTableData(header, databaseBinary, options, xs => new EnumKeyTableTable(xs)), - () => this.ItemTable = ExtractTableData(header, databaseBinary, options, xs => new ItemTable(xs)), - () => this.MonsterTable = ExtractTableData(header, databaseBinary, options, xs => new MonsterTable(xs)), - () => this.PersonTable = ExtractTableData(header, databaseBinary, options, xs => new PersonTable(xs)), - () => this.QuestTable = ExtractTableData(header, databaseBinary, options, xs => new QuestTable(xs)), - () => this.Test1Table = ExtractTableData(header, databaseBinary, options, xs => new Test1Table(xs)), - () => this.Test2Table = ExtractTableData(header, databaseBinary, options, xs => new Test2Table(xs)), - }; - - System.Threading.Tasks.Parallel.Invoke(new System.Threading.Tasks.ParallelOptions - { - MaxDegreeOfParallelism = maxDegreeOfParallelism - }, extracts); - } - - public ImmutableBuilder ToImmutableBuilder() - { - return new ImmutableBuilder(this); - } - - public DatabaseBuilder ToDatabaseBuilder() - { - var builder = new DatabaseBuilder(); - builder.Append(this.EnumKeyTableTable.GetRawDataUnsafe()); - builder.Append(this.ItemTable.GetRawDataUnsafe()); - builder.Append(this.MonsterTable.GetRawDataUnsafe()); - builder.Append(this.PersonTable.GetRawDataUnsafe()); - builder.Append(this.QuestTable.GetRawDataUnsafe()); - builder.Append(this.Test1Table.GetRawDataUnsafe()); - builder.Append(this.Test2Table.GetRawDataUnsafe()); - return builder; - } - - public DatabaseBuilder ToDatabaseBuilder(MessagePack.IFormatterResolver resolver) - { - var builder = new DatabaseBuilder(resolver); - builder.Append(this.EnumKeyTableTable.GetRawDataUnsafe()); - builder.Append(this.ItemTable.GetRawDataUnsafe()); - builder.Append(this.MonsterTable.GetRawDataUnsafe()); - builder.Append(this.PersonTable.GetRawDataUnsafe()); - builder.Append(this.QuestTable.GetRawDataUnsafe()); - builder.Append(this.Test1Table.GetRawDataUnsafe()); - builder.Append(this.Test2Table.GetRawDataUnsafe()); - return builder; - } - -#if !DISABLE_MASTERMEMORY_VALIDATOR - - public ValidateResult Validate() - { - var result = new ValidateResult(); - var database = new ValidationDatabase(new object[] - { - EnumKeyTableTable, - ItemTable, - MonsterTable, - PersonTable, - QuestTable, - Test1Table, - Test2Table, - }); - - ((ITableUniqueValidate)EnumKeyTableTable).ValidateUnique(result); - ValidateTable(EnumKeyTableTable.All, database, "Gender", EnumKeyTableTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)ItemTable).ValidateUnique(result); - ValidateTable(ItemTable.All, database, "ItemId", ItemTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)MonsterTable).ValidateUnique(result); - ValidateTable(MonsterTable.All, database, "MonsterId", MonsterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)PersonTable).ValidateUnique(result); - ValidateTable(PersonTable.All, database, "PersonId", PersonTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)QuestTable).ValidateUnique(result); - ValidateTable(QuestTable.All, database, "Id", QuestTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)Test1Table).ValidateUnique(result); - ValidateTable(Test1Table.All, database, "Id", Test1Table.PrimaryKeySelector, result); - ((ITableUniqueValidate)Test2Table).ValidateUnique(result); - ValidateTable(Test2Table.All, database, "Id", Test2Table.PrimaryKeySelector, result); - - return result; - } - -#endif - - static MasterMemory.Meta.MetaDatabase metaTable; - - public static object GetTable(MemoryDatabase db, string tableName) - { - switch (tableName) - { - case "enumkeytable": - return db.EnumKeyTableTable; - case "item": - return db.ItemTable; - case "monster": - return db.MonsterTable; - case "person": - return db.PersonTable; - case "quest_master": - return db.QuestTable; - case "Test1": - return db.Test1Table; - case "Test2": - return db.Test2Table; - - default: - return null; - } - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaDatabase GetMetaDatabase() - { - if (metaTable != null) return metaTable; - - var dict = new Dictionary(); - dict.Add("enumkeytable", ConsoleApp.Tables.EnumKeyTableTable.CreateMetaTable()); - dict.Add("item", ConsoleApp.Tables.ItemTable.CreateMetaTable()); - dict.Add("monster", ConsoleApp.Tables.MonsterTable.CreateMetaTable()); - dict.Add("person", ConsoleApp.Tables.PersonTable.CreateMetaTable()); - dict.Add("quest_master", ConsoleApp.Tables.QuestTable.CreateMetaTable()); - dict.Add("Test1", ConsoleApp.Tables.Test1Table.CreateMetaTable()); - dict.Add("Test2", ConsoleApp.Tables.Test2Table.CreateMetaTable()); - - metaTable = new MasterMemory.Meta.MetaDatabase(dict); - return metaTable; - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/EnumKeyTableTable.cs b/sandbox/ConsoleApp/Generated/Tables/EnumKeyTableTable.cs deleted file mode 100644 index c224fad..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/EnumKeyTableTable.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class EnumKeyTableTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public EnumKeyTableTable(EnumKeyTable[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Gender; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - public EnumKeyTable FindByGender(Gender key) - { - return FindUniqueCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, true); - } - - public bool TryFindByGender(Gender key, out EnumKeyTable result) - { - return TryFindUniqueCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, out result); - } - - public EnumKeyTable FindClosestByGender(Gender key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByGender(Gender min, Gender max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Gender", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(EnumKeyTable), typeof(EnumKeyTableTable), "enumkeytable", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(EnumKeyTable).GetProperty("Gender")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(EnumKeyTable).GetProperty("Gender"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/ItemTable.cs b/sandbox/ConsoleApp/Generated/Tables/ItemTable.cs deleted file mode 100644 index 36f14c2..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/ItemTable.cs +++ /dev/null @@ -1,110 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class ItemTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public ItemTable(Item[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.ItemId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Item FindByItemId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByItemId(int key, out Item result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Item FindClosestByItemId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByItemId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "ItemId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Item), typeof(ItemTable), "item", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Item).GetProperty("ItemId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Item).GetProperty("ItemId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/MonsterTable.cs b/sandbox/ConsoleApp/Generated/Tables/MonsterTable.cs deleted file mode 100644 index 42f97e9..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/MonsterTable.cs +++ /dev/null @@ -1,112 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class MonsterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public MonsterTable(Monster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.MonsterId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Monster FindByMonsterId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].MonsterId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByMonsterId(int key, out Monster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].MonsterId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Monster FindClosestByMonsterId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByMonsterId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "MonsterId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Monster), typeof(MonsterTable), "monster", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Monster).GetProperty("MonsterId")), - new MasterMemory.Meta.MetaProperty(typeof(Monster).GetProperty("Name")), - new MasterMemory.Meta.MetaProperty(typeof(Monster).GetProperty("MaxHp")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Monster).GetProperty("MonsterId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/PersonTable.cs b/sandbox/ConsoleApp/Generated/Tables/PersonTable.cs deleted file mode 100644 index 10186ff..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/PersonTable.cs +++ /dev/null @@ -1,183 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class PersonTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly Person[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - readonly Person[] secondaryIndex2; - readonly Func secondaryIndex2Selector; - readonly Person[] secondaryIndex1; - readonly Func secondaryIndex1Selector; - - public PersonTable(Person[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.PersonId; - this.secondaryIndex0Selector = x => x.Age; - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.Collections.Generic.Comparer.Default); - this.secondaryIndex2Selector = x => (x.Gender, x.Age); - this.secondaryIndex2 = CloneAndSortBy(this.secondaryIndex2Selector, System.Collections.Generic.Comparer<(Gender Gender, int Age)>.Default); - this.secondaryIndex1Selector = x => x.Gender; - this.secondaryIndex1 = CloneAndSortBy(this.secondaryIndex1Selector, System.Collections.Generic.Comparer.Default); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByAge => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - public RangeView SortByGenderAndAge => new RangeView(secondaryIndex2, 0, secondaryIndex2.Length - 1, true); - public RangeView SortByGender => new RangeView(secondaryIndex1, 0, secondaryIndex1.Length - 1, true); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Person FindByPersonId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].PersonId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByPersonId(int key, out Person result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].PersonId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Person FindClosestByPersonId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByPersonId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public RangeView FindByAge(int key) - { - return FindManyCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key); - } - - public RangeView FindClosestByAge(int key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByAge(int min, int max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public RangeView FindByGenderAndAge((Gender Gender, int Age) key) - { - return FindManyCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(Gender Gender, int Age)>.Default, key); - } - - public RangeView FindClosestByGenderAndAge((Gender Gender, int Age) key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(Gender Gender, int Age)>.Default, key, selectLower); - } - - public RangeView FindRangeByGenderAndAge((Gender Gender, int Age) min, (Gender Gender, int Age) max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(Gender Gender, int Age)>.Default, min, max, ascendant); - } - - public RangeView FindByGender(Gender key) - { - return FindManyCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer.Default, key); - } - - public RangeView FindClosestByGender(Gender key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByGender(Gender min, Gender max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "PersonId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Person), typeof(PersonTable), "person", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Person).GetProperty("PersonId")), - new MasterMemory.Meta.MetaProperty(typeof(Person).GetProperty("Age")), - new MasterMemory.Meta.MetaProperty(typeof(Person).GetProperty("Gender")), - new MasterMemory.Meta.MetaProperty(typeof(Person).GetProperty("Name")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Person).GetProperty("PersonId"), - }, true, true, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Person).GetProperty("Age"), - }, false, false, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Person).GetProperty("Gender"), - typeof(Person).GetProperty("Age"), - }, false, false, System.Collections.Generic.Comparer<(Gender Gender, int Age)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Person).GetProperty("Gender"), - }, false, false, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/QuestTable.cs b/sandbox/ConsoleApp/Generated/Tables/QuestTable.cs deleted file mode 100644 index 5fad527..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/QuestTable.cs +++ /dev/null @@ -1,114 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class QuestTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public QuestTable(Quest[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Quest FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Quest result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Quest FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Quest), typeof(QuestTable), "quest_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Quest).GetProperty("Id")), - new MasterMemory.Meta.MetaProperty(typeof(Quest).GetProperty("Name")), - new MasterMemory.Meta.MetaProperty(typeof(Quest).GetProperty("RewardId")), - new MasterMemory.Meta.MetaProperty(typeof(Quest).GetProperty("Cost")), - new MasterMemory.Meta.MetaProperty(typeof(Quest).GetProperty("MyProperty")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Quest).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/Test1Table.cs b/sandbox/ConsoleApp/Generated/Tables/Test1Table.cs deleted file mode 100644 index 70c2b6d..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/Test1Table.cs +++ /dev/null @@ -1,110 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class Test1Table : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public Test1Table(Test1[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Test1 FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Test1 result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Test1 FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Test1), typeof(Test1Table), "Test1", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Test1).GetProperty("Id")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Test1).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Generated/Tables/Test2Table.cs b/sandbox/ConsoleApp/Generated/Tables/Test2Table.cs deleted file mode 100644 index 76c3162..0000000 --- a/sandbox/ConsoleApp/Generated/Tables/Test2Table.cs +++ /dev/null @@ -1,110 +0,0 @@ -// -#pragma warning disable CS0105 -using ConsoleApp.Tables; -using ConsoleApp; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Buffers; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq.Expressions; -using System.Linq; -using System.Reflection; -using System.Text; -using System; - -namespace ConsoleApp.Tables -{ - public sealed partial class Test2Table : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public Test2Table(Test2[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Test2 FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Test2 result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Test2 FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Test2), typeof(Test2Table), "Test2", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Test2).GetProperty("Id")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Test2).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/sandbox/ConsoleApp/Program.cs b/sandbox/ConsoleApp/Program.cs index 6419f42..d7c25b1 100644 --- a/sandbox/ConsoleApp/Program.cs +++ b/sandbox/ConsoleApp/Program.cs @@ -1,21 +1,34 @@ using MasterMemory; -using System.Linq; using MessagePack; using System; -using System.IO; using System.Buffers; -using System.Linq.Expressions; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Reflection; -using System.Text; +using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; + + +[assembly: MasterMemoryGeneratorOptions( + Namespace = "ConsoleApp" // , + // IsReturnNullIfKeyNotFound = true, + // PrefixClassName = "Foo" +)] + +public class FooItem +{ + public bool TryFindByItemId(int key, out Item result) + { + result = default!; + return true; + } +} -// IValidatableƌؑΏۂɂȂ [MemoryTable("quest_master"), MessagePackObject(true)] public class Quest : IValidatable { - // UniqueKey̏ꍇValidateɃftHgŏď؂ [PrimaryKey] public int Id { get; set; } public string Name { get; set; } @@ -25,25 +38,19 @@ public class Quest : IValidatable void IValidatable.Validate(IValidator validator) { - // OL[IɎQƂRNVo var items = validator.GetReferenceSet(); - // RewardId0ȏ̂Ƃ(0͕ViV̂߂̓ʂȃtOƂ邽ߓ͂e) if (this.RewardId > 0) { - // Items̃}X^ɕK܂܂ĂȂΌ؃G[iG[oĂs͂ĂׂĂ̌،ʂo) items.Exists(x => x.RewardId, x => x.ItemId); } - // RXg10..20łȂΌ؃G[ validator.Validate(x => x.Cost >= 10); validator.Validate(x => x.Cost <= 20); - // ȉň͈͂xĂ΂Ȃ߁Af[^ZbgŜ̌؂Ɏg if (validator.CallOnce()) { var quests = validator.GetTableSet(); - // CfbNẌȊÕj[Nǂ̌(0͏d邽ߏĂ) quests.Where(x => x.RewardId != 0).Unique(x => x.RewardId); } } @@ -78,7 +85,7 @@ partial void OnAfterConstruct() namespace ConsoleApp { [MemoryTable("monster"), MessagePackObject(true)] - public class Monster + public partial class Monster { [PrimaryKey] public int MonsterId { get; private set; } @@ -203,6 +210,7 @@ public class Test1 public class Test2 { [PrimaryKey] + [Key(0)] public int Id { get; set; } } @@ -231,7 +239,7 @@ static void Main(string[] args) while ((reader.ReadValuesWithHeader() is Dictionary values)) { // create data without call constructor - var data = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(table.DataType); + var data = RuntimeHelpers.GetUninitializedObject(table.DataType); foreach (var prop in table.Properties) { diff --git a/sandbox/GeneratorSandbox/GeneratorSandbox.csproj b/sandbox/GeneratorSandbox/GeneratorSandbox.csproj new file mode 100644 index 0000000..95ac4af --- /dev/null +++ b/sandbox/GeneratorSandbox/GeneratorSandbox.csproj @@ -0,0 +1,30 @@ + + + + Exe + net9.0 + enable + enable + false + + + + + + + + + + + + + + Analyzer + false + + + + diff --git a/sandbox/GeneratorSandbox/Program.cs b/sandbox/GeneratorSandbox/Program.cs new file mode 100644 index 0000000..4892223 --- /dev/null +++ b/sandbox/GeneratorSandbox/Program.cs @@ -0,0 +1,72 @@ +using MasterMemory; +using MessagePack; +using GeneratorSandbox; +using System.Runtime.CompilerServices; + +//[assembly: MasterMemoryGeneratorOptions( +// Namespace = "Z", +// IsReturnNullIfKeyNotFound = true, +// PrefixClassName = "")] + +// to create database, use DatabaseBuilder and Append method. +var builder = new DatabaseBuilder(); +builder.Append(new Person[] +{ + new (){ PersonId = 0, Age = 13, Gender = Gender.Male, Name = "Dana Terry" }, + new (){ PersonId = 1, Age = 17, Gender = Gender.Male, Name = "Kirk Obrien" }, + new (){ PersonId = 2, Age = 31, Gender = Gender.Male, Name = "Wm Banks" }, + new (){ PersonId = 3, Age = 44, Gender = Gender.Male, Name = "Karl Benson" }, + new (){ PersonId = 4, Age = 23, Gender = Gender.Male, Name = "Jared Holland" }, + new (){ PersonId = 5, Age = 27, Gender = Gender.Female, Name = "Jeanne Phelps" }, + new (){ PersonId = 6, Age = 25, Gender = Gender.Female, Name = "Willie Rose" }, + new (){ PersonId = 7, Age = 11, Gender = Gender.Female, Name = "Shari Gutierrez" }, + new (){ PersonId = 8, Age = 63, Gender = Gender.Female, Name = "Lori Wilson" }, + new (){ PersonId = 9, Age = 34, Gender = Gender.Female, Name = "Lena Ramsey" }, +}); + +// build database binary(you can also use `WriteToStream` for save to file). +byte[] data = builder.Build(); + + +var db = new MemoryDatabase(data); + +// .PersonTable.FindByPersonId is fully typed by code-generation. +Person person = db.PersonTable.FindByPersonId(5); + +// Multiple key is also typed(***And * **), Return value is multiple if key is marked with `NonUnique`. +RangeView result = db.PersonTable.FindByGenderAndAge((Gender.Female, 23)); + +// Get nearest value(choose lower(default) or higher). +RangeView age1 = db.PersonTable.FindClosestByAge(31); + +// Get range(min-max inclusive). +RangeView age2 = db.PersonTable.FindRangeByAge(20, 29); + + +public enum Gender +{ + Male, Female, Unknown +} + + + +// table definition marked by MemoryTableAttribute. +// database-table must be serializable by MessagePack-CSsharp +[MemoryTable("person"), MessagePackObject(true)] +public record Person +{ + // index definition by attributes. + [PrimaryKey] + public required int PersonId { get; init; } + + // secondary index can add multiple(discriminated by index-number). + [SecondaryKey(0), NonUnique] + [SecondaryKey(1, keyOrder: 1), NonUnique] + public required int Age { get; init; } + + [SecondaryKey(2), NonUnique] + [SecondaryKey(1, keyOrder: 0), NonUnique] + public required Gender Gender { get; init; } + + public required string Name { get; init; } +} \ No newline at end of file diff --git a/sandbox/PerfTest/App.config b/sandbox/PerfTest/App.config deleted file mode 100644 index 323348d..0000000 --- a/sandbox/PerfTest/App.config +++ /dev/null @@ -1,51 +0,0 @@ - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sandbox/PerfTest/Engines/Dictionary_Test.cs b/sandbox/PerfTest/Engines/Dictionary_Test.cs deleted file mode 100644 index 73d3d43..0000000 --- a/sandbox/PerfTest/Engines/Dictionary_Test.cs +++ /dev/null @@ -1,216 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TestPerfLiteDB; - -namespace TestPerfLiteDB -{ - public class Dictionary_Test : ITest - { - private string _filename; - private int _count; - - Dictionary dict; - - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public Dictionary_Test(int count) - { - _count = count; - _filename = "dict-" + Guid.NewGuid().ToString("n") + ".db"; - dict = new Dictionary(); - } - - public void Insert() - { - foreach (var doc in Helper.GetDocs(_count)) - { - var v = new TestDoc - { - id = doc["_id"].AsInt32, - name = doc["name"].AsString, - lorem = doc["lorem"].AsString - }; - - dict.Add(v.id, v); - } - } - - public void Bulk() - { - - } - - public void CreateIndex() - { - - } - - public void Dispose() - { - - } - - public void Prepare() - { - - } - - public void Query() - { - for (var i = 0; i < _count; i++) - { - TestDoc d; - dict.TryGetValue(i, out d); - } - } - - public void Update() - { - - } - } - - public class ConcurrentDictionary_Test : ITest - { - private string _filename; - private int _count; - - ConcurrentDictionary dict; - - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public ConcurrentDictionary_Test(int count) - { - _count = count; - _filename = "concurrentdict-" + Guid.NewGuid().ToString("n") + ".db"; - dict = new ConcurrentDictionary(); - } - - public void Insert() - { - foreach (var doc in Helper.GetDocs(_count)) - { - var v = new TestDoc - { - id = doc["_id"].AsInt32, - name = doc["name"].AsString, - lorem = doc["lorem"].AsString - }; - - dict.TryAdd(v.id, v); - } - } - - public void Bulk() - { - - } - - public void CreateIndex() - { - - } - - public void Dispose() - { - - } - - public void Prepare() - { - - } - - public void Query() - { - for (var i = 0; i < _count; i++) - { - TestDoc d; - dict.TryGetValue(i, out d); - } - } - - public void Update() - { - - } - } - - public class ImmutableDictionary_Test : ITest - { - private string _filename; - private int _count; - - ImmutableDictionary dict; - - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public ImmutableDictionary_Test(int count) - { - _count = count; - _filename = "immutabledict-" + Guid.NewGuid().ToString("n") + ".db"; - //dict = new ImmutableDictionary(); - } - - public void Insert() - { - var builder = ImmutableDictionary.CreateBuilder(); - foreach (var doc in Helper.GetDocs(_count)) - { - var v = new TestDoc - { - id = doc["_id"].AsInt32, - name = doc["name"].AsString, - lorem = doc["lorem"].AsString - }; - - builder.Add(v.id, v); - } - - dict = builder.ToImmutableDictionary(); - } - - public void Bulk() - { - - } - - public void CreateIndex() - { - - } - - public void Dispose() - { - - } - - public void Prepare() - { - - } - - public void Query() - { - for (var i = 0; i < _count; i++) - { - TestDoc d; - dict.TryGetValue(i, out d); - } - } - - public void Update() - { - - } - } -} diff --git a/sandbox/PerfTest/Engines/ITest.cs b/sandbox/PerfTest/Engines/ITest.cs deleted file mode 100644 index fd260de..0000000 --- a/sandbox/PerfTest/Engines/ITest.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SQLite; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using LiteDB; - -namespace TestPerfLiteDB -{ - public interface ITest : IDisposable - { - int Count { get; } - int FileLength { get; } - - void Prepare(); - void Insert(); - void Bulk(); - void Update(); - void CreateIndex(); - void Query(); - //void Delete(); - //void Drop(); - } -} diff --git a/sandbox/PerfTest/Engines/LiteDB_Test.cs b/sandbox/PerfTest/Engines/LiteDB_Test.cs deleted file mode 100644 index 27bc448..0000000 --- a/sandbox/PerfTest/Engines/LiteDB_Test.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SQLite; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using LiteDB; - -namespace TestPerfLiteDB -{ - public class LiteDB_Test : ITest - { - private string _filename; - private LiteEngine _db; - private int _count; - - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public LiteDB_Test(int count, string password, LiteDB.FileOptions options) - { - _count = count; - _filename = "dblite-" + Guid.NewGuid().ToString("n") + ".db"; - - var disk = new FileDiskService(_filename, options); - - _db = new LiteEngine(disk, password); - } - - public LiteDB_Test(int count) - { - _count = count; - _filename = "dblite-" + Guid.NewGuid().ToString("n") + ".db"; - - var ms = new MemoryStream(); - var disk = new LiteDB.StreamDiskService(ms); - //var disk = new FileDiskService(_filename, options); - - _db = new LiteEngine(disk); - } - - public void Prepare() - { - } - - public void Insert() - { - foreach (var doc in Helper.GetDocs(_count)) - { - _db.Insert("col", doc); - } - } - - public void Bulk() - { - _db.Insert("col_bulk", Helper.GetDocs(_count)); - } - - public void Update() - { - foreach (var doc in Helper.GetDocs(_count)) - { - _db.Update("col", doc); - } - } - - public void CreateIndex() - { - _db.EnsureIndex("col", "name", false); - } - - public void Query() - { - for (var i = 0; i < _count; i++) - { - _db.Find("col", LiteDB.Query.EQ("_id", i)).Single(); - } - } - - public void Delete() - { - _db.Delete("col", LiteDB.Query.All()); - } - - public void Drop() - { - _db.DropCollection("col_bulk"); - } - - public void Dispose() - { - _db.Dispose(); - File.Delete(_filename); - } - } -} diff --git a/sandbox/PerfTest/Engines/MasterMemory_Test.cs b/sandbox/PerfTest/Engines/MasterMemory_Test.cs deleted file mode 100644 index 0dc6d8e..0000000 --- a/sandbox/PerfTest/Engines/MasterMemory_Test.cs +++ /dev/null @@ -1,86 +0,0 @@ -using MasterMemory; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestPerfLiteDB -{ - public class MasterMemory_Test : ITest - { - private string _filename; - private int _count; - - MemoryDatabase database; - - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public MasterMemory_Test(int count) - { - _count = count; - _filename = "mastermemorydatabase-" + Guid.NewGuid().ToString("n") + ".db"; - - } - - public IEnumerable MakeDoc() - { - foreach (var doc in Helper.GetDocs(_count)) - { - var v = new TestDoc - { - id = doc["_id"].AsInt32, - name = doc["name"].AsString, - lorem = doc["lorem"].AsString - }; - - yield return v; - } - } - - public void Insert() - { - var builder = new DatabaseBuilder(); - builder.Append(MakeDoc()); - var saved = builder.Build(); - File.WriteAllBytes(_filename, saved); - database = new MemoryDatabase(saved); - } - - public void Bulk() - { - - } - - public void CreateIndex() - { - - } - - public void Dispose() - { - - } - - public void Prepare() - { - - } - - public void Query() - { - for (var i = 0; i < _count; i++) - { - //TestDoc d; - database.TestDocTable.FindByid(i); - } - } - - public void Update() - { - - } - } -} diff --git a/sandbox/PerfTest/Engines/RavenDB_Test.cs b/sandbox/PerfTest/Engines/RavenDB_Test.cs deleted file mode 100644 index 7cac88b..0000000 --- a/sandbox/PerfTest/Engines/RavenDB_Test.cs +++ /dev/null @@ -1,127 +0,0 @@ -using Raven.Client; -using Raven.Client.Embedded; -using Raven.Client.Indexes; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestPerfLiteDB -{ - public class TestDocCreation : AbstractIndexCreationTask - { - public TestDocCreation() - { - Map = xs => xs.Select(x => new { x.id }); - } - } - - public class RavenDB_Test : ITest - { - private string _filename; - private int _count; - private bool isinmemory; - - IDocumentStore store; - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public RavenDB_Test(int count, bool isinmemory) - { - _count = count; - _filename = "ravendb-" + Guid.NewGuid().ToString("n") + ".db"; - this.isinmemory = isinmemory; - } - - public void Bulk() - { - if (isinmemory) - { - - - } - - //using (var store = new EmbeddableDocumentStore { RunInMemory = true }.Initialize()) - //{ - // using (var bulk = store.BulkInsert()) - // { - // bulk.Store(new MyClass { Id = 9999, MyProperty = 1000 }); - // } - - // var session = store.OpenSession(); - - // store.ExecuteIndex(new MyClassIndex()); - - // var huga = session.Load("MyClasses/9999"); - //} - } - - public void CreateIndex() - { - store.ExecuteIndex(new TestDocCreation()); - } - - public void Dispose() - { - store.Dispose(); - } - IEnumerable MakeDoc() - { - foreach (var doc in Helper.GetDocs(_count)) - { - var v = new TestDoc - { - id = doc["_id"].AsInt32, - name = doc["name"].AsString, - lorem = doc["lorem"].AsString - }; - - yield return v; - } - } - - - public void Insert() - { - - using (var bulk = store.BulkInsert()) - { - foreach (var item in MakeDoc()) - { - bulk.Store(item); - } - } - - } - - public void Prepare() - { - if (isinmemory) - { - store = new EmbeddableDocumentStore { RunInMemory = true }.Initialize(); - } - else - { - // store = new EmbeddableDocumentStore { RunInMemory = true }.Initialize(); - } - } - - public void Query() - { - for (var i = 0; i < _count; i++) - { - using (var session = store.OpenSession()) - { - session.Load("TestDoc/" + i); - } - } - } - - public void Update() - { - - } - } -} diff --git a/sandbox/PerfTest/Engines/SQLite_Test.cs b/sandbox/PerfTest/Engines/SQLite_Test.cs deleted file mode 100644 index ae73e5d..0000000 --- a/sandbox/PerfTest/Engines/SQLite_Test.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SQLite; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TestPerfLiteDB -{ - public class SQLite_Test : ITest - { - private string _filename; - private SQLiteConnection _db; - private int _count; - - public int Count { get { return _count; } } - public int FileLength { get { return (int)new FileInfo(_filename).Length; } } - - public SQLite_Test(int count, string password, bool journal, bool memory = false) - { - _count = count; - _filename = "sqlite-" + Guid.NewGuid().ToString("n") + ".db"; - - if (memory) - { - var cs = "Data Source=:memory:;New=True;"; - _db = new SQLiteConnection(cs); - } - else - { - var cs = "Data Source=" + _filename; - if (password != null) cs += "; Password=" + password; - if (journal == false) cs += "; Journal Mode=Off"; - _db = new SQLiteConnection(cs); - } - } - - public void Prepare() - { - _db.Open(); - - var table = new SQLiteCommand("CREATE TABLE col (id INTEGER NOT NULL PRIMARY KEY, name TEXT, lorem TEXT)", _db); - table.ExecuteNonQuery(); - - var table2 = new SQLiteCommand("CREATE TABLE col_bulk (id INTEGER NOT NULL PRIMARY KEY, name TEXT, lorem TEXT)", _db); - table2.ExecuteNonQuery(); - } - - public void Insert() - { - // standard insert is slow, mod same as Bulk - using (var trans = _db.BeginTransaction()) - { - var cmd = new SQLiteCommand("INSERT INTO col (id, name, lorem) VALUES (@id, @name, @lorem)", _db); - - cmd.Parameters.Add(new SQLiteParameter("id", DbType.Int32)); - cmd.Parameters.Add(new SQLiteParameter("name", DbType.String)); - cmd.Parameters.Add(new SQLiteParameter("lorem", DbType.String)); - - foreach (var doc in Helper.GetDocs(_count)) - { - cmd.Parameters["id"].Value = doc["_id"].AsInt32; - cmd.Parameters["name"].Value = doc["name"].AsString; - cmd.Parameters["lorem"].Value = doc["lorem"].AsString; - - cmd.ExecuteNonQuery(); - } - - trans.Commit(); - } - } - - public void Bulk() - { - using (var trans = _db.BeginTransaction()) - { - var cmd = new SQLiteCommand("INSERT INTO col_bulk (id, name, lorem) VALUES (@id, @name, @lorem)", _db); - - cmd.Parameters.Add(new SQLiteParameter("id", DbType.Int32)); - cmd.Parameters.Add(new SQLiteParameter("name", DbType.String)); - cmd.Parameters.Add(new SQLiteParameter("lorem", DbType.String)); - - foreach (var doc in Helper.GetDocs(_count)) - { - cmd.Parameters["id"].Value = doc["_id"].AsInt32; - cmd.Parameters["name"].Value = doc["name"].AsString; - cmd.Parameters["lorem"].Value = doc["lorem"].AsString; - - cmd.ExecuteNonQuery(); - } - - trans.Commit(); - } - } - - public void Update() - { - var cmd = new SQLiteCommand("UPDATE col SET name = @name, lorem = @lorem WHERE id = @id", _db); - - cmd.Parameters.Add(new SQLiteParameter("id", DbType.Int32)); - cmd.Parameters.Add(new SQLiteParameter("name", DbType.String)); - cmd.Parameters.Add(new SQLiteParameter("lorem", DbType.String)); - - foreach (var doc in Helper.GetDocs(_count)) - { - cmd.Parameters["id"].Value = doc["_id"].AsInt32; - cmd.Parameters["name"].Value = doc["name"].AsString; - cmd.Parameters["lorem"].Value = doc["lorem"].AsString; - - cmd.ExecuteNonQuery(); - } - } - - public void CreateIndex() - { - var cmd = new SQLiteCommand("CREATE INDEX idx1 ON col (name)", _db); - - cmd.ExecuteNonQuery(); - } - - public void Query() - { - var cmd = new SQLiteCommand("SELECT * FROM col WHERE id = @id", _db); - - cmd.Parameters.Add(new SQLiteParameter("id", DbType.Int32)); - - for (var i = 0; i < _count; i++) - { - cmd.Parameters["id"].Value = i; - - var r = cmd.ExecuteReader(); - - r.Read(); - - var name = r.GetString(1); - var lorem = r.GetString(2); - - r.Close(); - } - } - - public void Delete() - { - var cmd = new SQLiteCommand("DELETE FROM col", _db); - - cmd.ExecuteNonQuery(); - } - - public void Drop() - { - var cmd = new SQLiteCommand("DROP TABLE col_bulk", _db); - - cmd.ExecuteNonQuery(); - } - - public void Dispose() - { - _db.Dispose(); - } - } -} diff --git a/sandbox/PerfTest/Generated/DatabaseBuilder.cs b/sandbox/PerfTest/Generated/DatabaseBuilder.cs deleted file mode 100644 index d73b0eb..0000000 --- a/sandbox/PerfTest/Generated/DatabaseBuilder.cs +++ /dev/null @@ -1,27 +0,0 @@ -using LiteDB; -using MasterMemory.Annotations; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Data.SQLite; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using ZeroFormatter; -using TestPerfLiteDB.Tables; - -namespace TestPerfLiteDB -{ - public sealed class DatabaseBuilder : DatabaseBuilderBase - { - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.id, System.Collections.Generic.Comparer.Default); - return this; - } - - } -} \ No newline at end of file diff --git a/sandbox/PerfTest/Generated/ImmutableBuilder.cs b/sandbox/PerfTest/Generated/ImmutableBuilder.cs deleted file mode 100644 index 18e7c5f..0000000 --- a/sandbox/PerfTest/Generated/ImmutableBuilder.cs +++ /dev/null @@ -1,65 +0,0 @@ -using LiteDB; -using MasterMemory.Annotations; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Data.SQLite; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using ZeroFormatter; -using TestPerfLiteDB.Tables; - -namespace TestPerfLiteDB -{ - public sealed class ImmutableBuilder : ImmutableBuilderBase - { - MemoryDatabase memory; - - public ImmutableBuilder(MemoryDatabase memory) - { - this.memory = memory; - } - - public MemoryDatabase Build() - { - return memory; - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.id, System.Collections.Generic.Comparer.Default); - var table = new TestDocTable(newData); - memory = new MemoryDatabase( - table - - ); - } - - public void RemoveTestDoc(int[] keys) - { - var data = RemoveCore(memory.TestDocTable.GetRawDataUnsafe(), keys, x => x.id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.id, System.Collections.Generic.Comparer.Default); - var table = new TestDocTable(newData); - memory = new MemoryDatabase( - table - - ); - } - - public void Diff(TestDoc[] addOrReplaceData) - { - var data = DiffCore(memory.TestDocTable.GetRawDataUnsafe(), addOrReplaceData, x => x.id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.id, System.Collections.Generic.Comparer.Default); - var table = new TestDocTable(newData); - memory = new MemoryDatabase( - table - - ); - } - - } -} \ No newline at end of file diff --git a/sandbox/PerfTest/Generated/MemoryDatabase.cs b/sandbox/PerfTest/Generated/MemoryDatabase.cs deleted file mode 100644 index f12cb01..0000000 --- a/sandbox/PerfTest/Generated/MemoryDatabase.cs +++ /dev/null @@ -1,51 +0,0 @@ -using LiteDB; -using MasterMemory.Annotations; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Data.SQLite; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using TestPerfLiteDB; -using ZeroFormatter; -using TestPerfLiteDB.Tables; - -namespace TestPerfLiteDB -{ - public sealed class MemoryDatabase : MemoryDatabaseBase - { - public TestDocTable TestDocTable { get; private set; } - - public MemoryDatabase( - TestDocTable TestDocTable - ) - { - this.TestDocTable = TestDocTable; - } - - public MemoryDatabase(byte[] databaseBinary, bool internString = true, IFormatterResolver formatterResolver = null) - : base(databaseBinary, internString, formatterResolver) - { - } - - protected override void Init(Dictionary header, int headerOffset, byte[] databaseBinary, IFormatterResolver resolver) - { - this.TestDocTable = ExtractTableData(header, headerOffset, databaseBinary, resolver, xs => new TestDocTable(xs)); - } - - public ImmutableBuilder ToImmutableBuilder() - { - return new ImmutableBuilder(this); - } - - public DatabaseBuilder ToDatabaseBuilder() - { - var builder = new DatabaseBuilder(); - builder.Append(this.TestDocTable.GetRawDataUnsafe()); - return builder; - } - } -} \ No newline at end of file diff --git a/sandbox/PerfTest/Generated/Tables/TestDocTable.cs b/sandbox/PerfTest/Generated/Tables/TestDocTable.cs deleted file mode 100644 index d5397a7..0000000 --- a/sandbox/PerfTest/Generated/Tables/TestDocTable.cs +++ /dev/null @@ -1,46 +0,0 @@ -using MasterMemory; -using System; -using System.Runtime.CompilerServices; - -namespace TestPerfLiteDB.Tables -{ - public sealed partial class TestDocTable : TableBase - { - readonly Func primaryIndexSelector; - - - public TestDocTable(TestDoc[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.id; - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public TestDoc FindByid(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = lo + ((hi - lo) >> 1); - var selected = data[mid].id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return default; - } - - public TestDoc FindClosestByid(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByid(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - } -} \ No newline at end of file diff --git a/sandbox/PerfTest/PerfTest.csproj b/sandbox/PerfTest/PerfTest.csproj deleted file mode 100644 index fb95938..0000000 --- a/sandbox/PerfTest/PerfTest.csproj +++ /dev/null @@ -1,204 +0,0 @@ - - - - - Debug - AnyCPU - {36EF0213-98F0-40F5-978F-EAEFF0F8FC42} - Exe - Properties - PerfTest - PerfTest - v4.6.1 - 512 - true - - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll - - - ..\..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll - - - ..\..\packages\EnyimMemcachedCore.2.2.4\lib\netstandard2.0\EnyimMemcachedCore.dll - - - ..\..\packages\LiteDB.4.1.4\lib\net40\LiteDB.dll - - - ..\..\packages\MessagePack.1.7.3.7\lib\net45\MessagePack.dll - - - ..\..\packages\Microsoft.AspNetCore.Http.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll - - - ..\..\packages\Microsoft.AspNetCore.Http.Features.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Features.dll - - - ..\..\packages\Microsoft.Extensions.Caching.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Caching.Abstractions.dll - - - ..\..\packages\Microsoft.Extensions.Configuration.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll - - - ..\..\packages\Microsoft.Extensions.Configuration.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll - - - ..\..\packages\Microsoft.Extensions.Configuration.Binder.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll - - - ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - ..\..\packages\Microsoft.Extensions.Logging.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll - - - ..\..\packages\Microsoft.Extensions.Options.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Options.dll - - - ..\..\packages\Microsoft.Extensions.Options.ConfigurationExtensions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Options.ConfigurationExtensions.dll - - - ..\..\packages\Microsoft.Extensions.Primitives.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll - - - ..\..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll - - - ..\..\packages\Newtonsoft.Json.Bson.1.0.2\lib\net45\Newtonsoft.Json.Bson.dll - - - ..\..\packages\RavenDB.Database.3.5.2\lib\net45\Raven.Abstractions.dll - True - - - ..\..\packages\RavenDB.Client.3.5.2\lib\net45\Raven.Client.Lightweight.dll - True - - - ..\..\packages\RavenDB.Database.3.5.2\lib\net45\Raven.Database.dll - True - - - - ..\..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll - - - ..\..\packages\System.Collections.Immutable.1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll - - - ..\..\packages\System.ComponentModel.Annotations.4.5.0\lib\net461\System.ComponentModel.Annotations.dll - - - - - - ..\..\packages\System.Data.SQLite.Core.1.0.111.0\lib\net46\System.Data.SQLite.dll - - - ..\..\packages\System.Data.SQLite.EF6.1.0.111.0\lib\net46\System.Data.SQLite.EF6.dll - - - ..\..\packages\System.Data.SQLite.Linq.1.0.111.0\lib\net46\System.Data.SQLite.Linq.dll - - - ..\..\packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll - - - - ..\..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll - - - ..\..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll - - - ..\..\packages\System.Text.Encodings.Web.4.5.0\lib\netstandard2.0\System.Text.Encodings.Web.dll - - - ..\..\packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll - - - ..\..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll - - - - - - - - - ..\..\packages\ZeroFormatter.1.6.4\lib\net45\ZeroFormatter.dll - - - ..\..\packages\ZeroFormatter.Interfaces.1.6.4\lib\net45\ZeroFormatter.Interfaces.dll - - - - - - - - - - - - - - - - - - - - - - - - {a13f40dd-7777-4e97-9fc4-6324722ca964} - MasterMemory.Annotations - - - {d2720bbb-c233-4a1e-9768-1f00c9602180} - MasterMemory - - - - - - - - このプロジェクトは、このコンピューター上にない NuGet パッケージを参照しています。それらのパッケージをダウンロードするには、[NuGet パッケージの復元] を使用します。詳細については、http://go.microsoft.com/fwlink/?LinkID=322105 を参照してください。見つからないファイルは {0} です。 - - - - - diff --git a/sandbox/PerfTest/Program.cs b/sandbox/PerfTest/Program.cs deleted file mode 100644 index a30bb7a..0000000 --- a/sandbox/PerfTest/Program.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.SQLite; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using LiteDB; -using System.IO; - -// based test code -> https://github.com/mbdavid/LiteDB-Perf - -namespace TestPerfLiteDB -{ - class Program - { - static void Main(string[] args) - { - RunTest("LiteDB: default", new LiteDB_Test(5000, null, new LiteDB.FileOptions { Journal = true, FileMode = LiteDB.FileMode.Shared })); - RunTest("LiteDB: encrypted", new LiteDB_Test(5000, "mypass", new LiteDB.FileOptions { Journal = true, FileMode = LiteDB.FileMode.Shared })); - RunTest("LiteDB: exclusive no journal", new LiteDB_Test(5000, null, new LiteDB.FileOptions { Journal = false, FileMode = LiteDB.FileMode.Exclusive })); - RunTest("LiteDB: in-memory", new LiteDB_Test(5000)); - - RunTest("SQLite: default", new SQLite_Test(5000, null, true)); - RunTest("SQLite: encrypted", new SQLite_Test(5000, "mypass", true)); - RunTest("SQLite: no journal", new SQLite_Test(5000, null, false)); - RunTest("SQLite: in-memory", new SQLite_Test(5000, null, false, true)); - - - - RunTest("Dictionary", new Dictionary_Test(5000)); - RunTest("ConcurrentDictionary", new ConcurrentDictionary_Test(5000)); - RunTest("ImmutableDictionary", new ImmutableDictionary_Test(5000)); - - RunTest("MasterMemory", new MasterMemory_Test(5000)); - - Console.ReadKey(); - - // RunTest("RavenDB: in-memory", new RavenDB_Test(5000, true)); - } - - static void RunTest(string name, ITest test) - { - var title = name + " - " + test.Count + " records"; - Console.WriteLine(title); - Console.WriteLine("=".PadLeft(title.Length, '=')); - - test.Prepare(); - - test.Run("Insert", test.Insert, true); - test.Run("Bulk", test.Bulk, true); - test.Run("CreateIndex", test.CreateIndex, true); - test.Run("Query", test.Query, false); - test.Run("Query", test.Query, false); - test.Run("Query", test.Query, false); - test.Run("Query", test.Query, false); - - try - { - Console.WriteLine("FileLength : " + Math.Round((double)test.FileLength / (double)1024, 2).ToString().PadLeft(5, ' ') + " kb"); - } - catch (System.IO.FileNotFoundException) - { - } - - test.Dispose(); - - Console.WriteLine(); - - } - } -} \ No newline at end of file diff --git a/sandbox/PerfTest/Properties/AssemblyInfo.cs b/sandbox/PerfTest/Properties/AssemblyInfo.cs deleted file mode 100644 index 1c8c89b..0000000 --- a/sandbox/PerfTest/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("PerfTest")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("PerfTest")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("36ef0213-98f0-40f5-978f-eaeff0f8fc42")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sandbox/PerfTest/Utils/Helper.cs b/sandbox/PerfTest/Utils/Helper.cs deleted file mode 100644 index a36702c..0000000 --- a/sandbox/PerfTest/Utils/Helper.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.SQLite; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using LiteDB; -using ZeroFormatter; -using MessagePack; -using MasterMemory.Annotations; - -namespace TestPerfLiteDB -{ - [MemoryTable("TestDoc"), MessagePackObject(true)] - public class TestDoc - { - [PrimaryKey] - public int id { get; set; } - public string name { get; set; } - public string lorem { get; set; } - } - - static class Helper - { - public static void Run(this ITest test, string name, Action action, bool dryrun) - { - var sw = new Stopwatch(); - - System.GC.Collect(2, GCCollectionMode.Forced, blocking: true); - sw.Start(); - action(); - sw.Stop(); - - var time = sw.ElapsedMilliseconds.ToString().PadLeft(5, ' '); - var seg = Math.Round(test.Count / sw.Elapsed.TotalSeconds).ToString().PadLeft(8, ' '); - - if (!dryrun) - { - Console.WriteLine(name.PadRight(15, ' ') + ": " + - time + " ms - " + - seg + " records/second"); - } - } - - public static IEnumerable GetDocs(int count) - { - for (var i = 0; i < count; i++) - { - yield return new BsonDocument - { - { "_id", i }, - { "name", Guid.NewGuid().ToString() }, - { "lorem", LoremIpsum(3, 5, 2, 3, 3) } - }; - } - } - - public static string LoremIpsum(int minWords, int maxWords, - int minSentences, int maxSentences, - int numParagraphs) - { - var words = new[] { "lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", - "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod", - "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat" }; - - var rand = new Random(DateTime.Now.Millisecond); - var numSentences = rand.Next(maxSentences - minSentences) + minSentences + 1; - var numWords = rand.Next(maxWords - minWords) + minWords + 1; - - var result = new StringBuilder(); - - for (int p = 0; p < numParagraphs; p++) - { - for (int s = 0; s < numSentences; s++) - { - for (int w = 0; w < numWords; w++) - { - if (w > 0) { result.Append(" "); } - result.Append(words[rand.Next(words.Length)]); - } - result.Append(". "); - } - result.AppendLine(); - } - - return result.ToString(); - } - } -} diff --git a/sandbox/PerfTest/packages.config b/sandbox/PerfTest/packages.config deleted file mode 100644 index c150152..0000000 --- a/sandbox/PerfTest/packages.config +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sandbox/PerfTest2/PerfTest2.csproj b/sandbox/PerfTest2/PerfTest2.csproj index f9d13a9..1faae25 100644 --- a/sandbox/PerfTest2/PerfTest2.csproj +++ b/sandbox/PerfTest2/PerfTest2.csproj @@ -1,19 +1,23 @@ - - Exe - net6.0 - false - + + Exe + net9.0 + false + 1701;1702;NU1904 + - - - - - + + + + - - - + + + + Analyzer + false + + diff --git a/src/MasterMemory.Annotations/MasterMemory.Annotations.csproj b/src/MasterMemory.Annotations/MasterMemory.Annotations.csproj index ffcda66..a1cc7c9 100644 --- a/src/MasterMemory.Annotations/MasterMemory.Annotations.csproj +++ b/src/MasterMemory.Annotations/MasterMemory.Annotations.csproj @@ -1,26 +1,27 @@  - - netstandard2.0 + + netstandard2.0 + 13 + Library + enable + False + Cysharp + true + 1701;1702;1705;1591 - Library - False - Cysharp - true - 1701;1702;1705;1591 - - - MasterMemory.Annotations - $(Version) - Cysharp - Cysharp - Attributes of MasterMemory. - https://github.com/Cysharp/MasterMemory - $(PackageProjectUrl) - git - database, embedded, inmemory, unity - MasterMemory - true - + + MasterMemory.Annotations + $(Version) + Cysharp + Cysharp + Attributes of MasterMemory. + https://github.com/Cysharp/MasterMemory + $(PackageProjectUrl) + git + database, embedded, inmemory, unity + MasterMemory + true + diff --git a/src/MasterMemory.Generator/MasterMemory.Generator.csproj b/src/MasterMemory.Generator/MasterMemory.Generator.csproj deleted file mode 100644 index bbd9041..0000000 --- a/src/MasterMemory.Generator/MasterMemory.Generator.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - Exe - net5.0;net6.0 - latest - true - dotnet-mmgen - - - - - MasterMemory.Generator - $(Version) - Cysharp - Cysharp - Code Generator of MasterMemory. - https://github.com/Cysharp/MasterMemory - $(PackageProjectUrl) - git - database, embedded, inmemory, unity - true - - - - - - - - - - - diff --git a/src/MasterMemory.Generator/Program.cs b/src/MasterMemory.Generator/Program.cs deleted file mode 100644 index 296569a..0000000 --- a/src/MasterMemory.Generator/Program.cs +++ /dev/null @@ -1,36 +0,0 @@ -using ConsoleAppFramework; -using MasterMemory.GeneratorCore; -using Microsoft.Extensions.Hosting; -using System; -using System.Diagnostics; -using System.Threading.Tasks; - -namespace MasterMemory.Generator -{ - public class Program : ConsoleAppBase - { - static async Task Main(string[] args) - { - await Host.CreateDefaultBuilder() - .ConfigureLogging(x => x.ReplaceToSimpleConsole()) - .RunConsoleAppFrameworkAsync(args); - } - - public void Execute( - [Option("i", "Input file directory(search recursive).")]string inputDirectory, - [Option("o", "Output file directory.")]string outputDirectory, - [Option("n", "Namespace of generated files.")]string usingNamespace, - [Option("p", "Prefix of class names.")]string prefixClassName = "", - [Option("c", "Add immutable constructor to MemoryTable class.")]bool addImmutableConstructor = false, - [Option("t", "Return null if key not found on unique find method.")]bool returnNullIfKeyNotFound = false, - [Option("f", "Overwrite generated files if the content is unchanged.")]bool forceOverwrite = false) - { - var sw = Stopwatch.StartNew(); - Console.WriteLine("Start MasterMemory CodeGeneration"); - - new CodeGenerator().GenerateFile(usingNamespace, inputDirectory, outputDirectory, prefixClassName, addImmutableConstructor, !returnNullIfKeyNotFound, forceOverwrite, x => Console.WriteLine(x)); - - Console.WriteLine("Complete MasterMemory CodeGeneration, elapsed:" + sw.Elapsed); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Generator/Properties/launchSettings.json b/src/MasterMemory.Generator/Properties/launchSettings.json deleted file mode 100644 index 087bd84..0000000 --- a/src/MasterMemory.Generator/Properties/launchSettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "profiles": { - "MasterMemory.Generator": { - "commandName": "Project", - "commandLineArgs": "-i \"C:\\GitHubRepositories\\MasterMemory\\sandbox\\COnsoleApp\" -o \"C:\\GitHubRepositories\\MasterMemory\\sandbox\\ConsoleApp\\Generated\" -n ConsoleApp" - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.GeneratorCore/CodeGenerator.cs b/src/MasterMemory.GeneratorCore/CodeGenerator.cs deleted file mode 100644 index 1e67b18..0000000 --- a/src/MasterMemory.GeneratorCore/CodeGenerator.cs +++ /dev/null @@ -1,456 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Editing; -using Microsoft.CodeAnalysis.Formatting; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace MasterMemory.GeneratorCore -{ - public class CodeGenerator - { - static readonly Encoding NoBomUtf8 = new UTF8Encoding(false); - - public void GenerateFile(string usingNamespace, string inputDirectory, string outputDirectory, string prefixClassName, bool addImmutableConstructor, bool throwIfKeyNotFound, bool forceOverwrite, Action logger) - { - prefixClassName ??= ""; - var list = new List(); - - // Collect - if (inputDirectory.EndsWith(".csproj")) - { - throw new InvalidOperationException("Path must be directory but it is csproj. inputDirectory:" + inputDirectory); - } - - foreach (var item in Directory.GetFiles(inputDirectory, "*.cs", SearchOption.AllDirectories)) - { - list.AddRange(CreateGenerationContext(item)); - } - - list.Sort((a, b) => string.Compare(a.ClassName, b.ClassName, StringComparison.Ordinal)); - - if (list.Count == 0) - { - throw new InvalidOperationException("Not found MemoryTable files, inputDir:" + inputDirectory); - } - - // Output - { - if (!Directory.Exists(outputDirectory)) - { - Directory.CreateDirectory(outputDirectory); - } - - var usingStrings = string.Join(Environment.NewLine, list.SelectMany(x => x.UsingStrings).Distinct().OrderBy(x => x, StringComparer.Ordinal)); - - var builderTemplate = new DatabaseBuilderTemplate(); - var databaseTemplate = new MemoryDatabaseTemplate(); - var immutableBuilderTemplate = new ImmutableBuilderTemplate(); - var resolverTemplate = new MessagePackResolverTemplate(); - builderTemplate.Namespace = databaseTemplate.Namespace = immutableBuilderTemplate.Namespace = resolverTemplate.Namespace = usingNamespace; - builderTemplate.PrefixClassName = databaseTemplate.PrefixClassName = immutableBuilderTemplate.PrefixClassName = resolverTemplate.PrefixClassName = prefixClassName; - builderTemplate.Using = databaseTemplate.Using = immutableBuilderTemplate.Using = resolverTemplate.Using = (usingStrings + Environment.NewLine + ("using " + usingNamespace + ".Tables;")); - builderTemplate.GenerationContexts = databaseTemplate.GenerationContexts = immutableBuilderTemplate.GenerationContexts = resolverTemplate.GenerationContexts = list.ToArray(); - - logger(WriteToFile(outputDirectory, builderTemplate.ClassName, builderTemplate.TransformText(), forceOverwrite)); - logger(WriteToFile(outputDirectory, immutableBuilderTemplate.ClassName, immutableBuilderTemplate.TransformText(), forceOverwrite)); - logger(WriteToFile(outputDirectory, databaseTemplate.ClassName, databaseTemplate.TransformText(), forceOverwrite)); - logger(WriteToFile(outputDirectory, resolverTemplate.ClassName, resolverTemplate.TransformText(), forceOverwrite)); - } - { - var tableDir = Path.Combine(outputDirectory, "Tables"); - if (!Directory.Exists(tableDir)) - { - Directory.CreateDirectory(tableDir); - } - - foreach (var context in list) - { - var template = new TableTemplate() - { - Namespace = usingNamespace, - GenerationContext = context, - Using = string.Join(Environment.NewLine, context.UsingStrings), - ThrowKeyIfNotFound = throwIfKeyNotFound - }; - - logger(WriteToFile(tableDir, context.ClassName + "Table", template.TransformText(), forceOverwrite)); - } - } - // Modify - { - if (addImmutableConstructor) - { - var workspace = new AdhocWorkspace(); - var byFilePath = list.GroupBy(x => x.InputFilePath); - - foreach (var context in byFilePath) - { - var newFile = BuildRecordConstructorFile(workspace, context.Select(x => x.OriginalClassDeclaration)); - if (newFile != null) - { - File.WriteAllText(context.Key, newFile, NoBomUtf8); - logger("Modified " + context.Key); - } - } - } - } - } - - static string NormalizeNewLines(string content) - { - // The T4 generated code may be text with mixed line ending types. (CR + CRLF) - // We need to normalize the line ending type in each Operating Systems. (e.g. Windows=CRLF, Linux/macOS=LF) - return content.Replace("\r\n", "\n").Replace("\n", Environment.NewLine); - } - - static string WriteToFile(string directory, string fileName, string content, bool forceOverwrite) - { - var path = Path.Combine(directory, fileName + ".cs"); - var contentBytes = Encoding.UTF8.GetBytes(NormalizeNewLines(content)); - - // If the generated content is unchanged, skip the write. - if (!forceOverwrite && File.Exists(path)) - { - if (new FileInfo(path).Length == contentBytes.Length && contentBytes.AsSpan().SequenceEqual(File.ReadAllBytes(path))) - { - return $"Generate {fileName} to: {path} (Skipped)"; - } - } - - File.WriteAllBytes(path, contentBytes); - return $"Generate {fileName} to: {path}"; - } - - IEnumerable CreateGenerationContext(string filePath) - { - var syntax = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(File.ReadAllText(filePath)); - var root = syntax.GetRoot(); - - var classDeclarations = root.DescendantNodes().OfType().ToArray(); - if (classDeclarations.Length == 0) yield break; - - var ns = root.DescendantNodes().OfType() - .Select(x => "using " + x.Name.ToFullStringTrim() + ";") - .ToArray(); - - var usingStrings = root.DescendantNodes() - .OfType() - .Select(x => x.ToFullString().Trim()) - .Concat(new[] { "using MasterMemory", "using MasterMemory.Validation", "using System", "using System.Collections.Generic" }) - .Concat(ns) - .Select(x => x.Trim(';') + ";") - .Distinct() - .OrderBy(x => x, StringComparer.Ordinal) - .ToArray(); - - foreach (var classDecl in classDeclarations) - { - var context = new GenerationContext(); - - foreach (var attr in classDecl.AttributeLists.SelectMany(x => x.Attributes)) - { - var attrName = attr.Name.ToFullString().Trim(); - if (attrName == "MemoryTable" || attrName == "MasterMemory.Annotations.MemoryTable") - { - context.ClassName = classDecl.Identifier.ToFullString().Trim(); - context.MemoryTableName = AttributeExpressionToString(attr.ArgumentList.Arguments[0].Expression) ?? context.ClassName; - - var members = classDecl.Members.OfType() - .Select(x => ExtractPropertyAttribute(x)) - .ToArray(); - - var primaryKey = AggregatePrimaryKey(members.Where(x => x.Item1 != null).Select(x => x.Item1)); - if (primaryKey.Properties.Length == 0) - { - throw new InvalidOperationException("MemoryTable does not found PrimaryKey property, Type:" + context.ClassName); - } - - var secondaryKeys = members.SelectMany(x => x.Item2).GroupBy(x => x.IndexNo).Select(x => AggregateSecondaryKey(x)).ToArray(); - var properties = members.Where(x => x.Item3 != null).Select(x => new Property - { - Type = x.Item3.Type.ToFullStringTrim(), - Name = x.Item3.Identifier.Text, - }).ToArray(); - - context.PrimaryKey = primaryKey; - context.SecondaryKeys = secondaryKeys; - context.Properties = properties; - } - } - - if (context.PrimaryKey != null) - { - context.UsingStrings = usingStrings; - context.OriginalClassDeclaration = classDecl; - context.InputFilePath = filePath; - yield return context; - } - } - } - - (PrimaryKey, List, PropertyDeclarationSyntax) ExtractPropertyAttribute(PropertyDeclarationSyntax property) - { - // Attribute Parterns: - // Primarykey(keyOrder = 0) - // SecondaryKey(indexNo, keyOrder = 0) - // NonUnique - // StringComparisonOption - - PrimaryKey resultPrimaryKey = default; - List secondaryKeys = new List(); - bool isSerializableProperty = true; - - foreach (var attrList in property.AttributeLists) - { - var hasNonUnique = false; - PrimaryKey primaryKey = default; - SecondaryKey secondaryKey = default; - - foreach (var attr in attrList.Attributes) - { - var attrName = attr.Name.ToFullString().Trim(); - if (attrName == "PrimaryKey" || attrName == "MasterMemory.Annotations.PrimaryKey") - { - if (resultPrimaryKey != null) - { - throw new InvalidOperationException("Duplicate PrimaryKey:" + property.Type.ToFullString() + "." + property.Identifier.ToFullString()); - } - - primaryKey = new PrimaryKey(); - var keyProperty = new KeyProperty() - { - Name = property.Identifier.ToFullStringTrim(), - TypeName = property.Type.ToFullStringTrim() - }; - - foreach (var arg in attr.ArgumentList?.Arguments ?? default) - { - keyProperty.KeyOrder = (int)((arg.Expression as LiteralExpressionSyntax).Token.Value); - } - - primaryKey.Properties = new[] { keyProperty }; - } - else if (attrName == "SecondaryKey" || attrName == "MasterMemory.Annotations.SecondaryKey") - { - if (secondaryKey != null) - { - throw new InvalidOperationException("Duplicate SecondaryKey, doesn't allow to add multiple attribute in same attribute list:" + property.Type.ToFullString() + "." + property.Identifier.ToFullString()); - } - - secondaryKey = new SecondaryKey(); - var keyProperty = new KeyProperty() - { - Name = property.Identifier.ToFullStringTrim(), - TypeName = property.Type.ToFullStringTrim() - }; - - var args = attr.ArgumentList.Arguments; - secondaryKey.IndexNo = (int)((args[0].Expression as LiteralExpressionSyntax).Token.Value); - if (args.Count == 2) - { - keyProperty.KeyOrder = (int)((args[1].Expression as LiteralExpressionSyntax).Token.Value); - } - secondaryKey.Properties = new[] { keyProperty }; - } - else if (attrName == "NonUnique" || attrName == "MasterMemory.Annotations.NonUnique") - { - hasNonUnique = true; - } - else if (attrName == "StringComparisonOption" || attrName == "MasterMemory.Annotations.StringComparisonOption") - { - var option = (attr.ArgumentList.Arguments[0].Expression as MemberAccessExpressionSyntax).ToFullStringTrim(); - if (primaryKey != null) - { - primaryKey.StringComparisonOption = option; - } - if (secondaryKey != null) - { - secondaryKey.StringComparisonOption = option; - } - } - else if (!property.Modifiers.Any(SyntaxKind.PublicKeyword) - || attrName == "IgnoreMember" || attrName == "MessagePack.IgnoreMember" - || attrName == "IgnoreDataMember" || attrName == "System.Runtime.Serialization.IgnoreDataMember") - { - isSerializableProperty = false; - } - } - - if (hasNonUnique) - { - if (primaryKey != null) - { - primaryKey.IsNonUnique = true; - } - if (secondaryKey != null) - { - secondaryKey.IsNonUnique = true; - } - } - - if (primaryKey != null) - { - resultPrimaryKey = primaryKey; - } - if (secondaryKey != null) - { - secondaryKeys.Add(secondaryKey); - } - } - - return (resultPrimaryKey, secondaryKeys, isSerializableProperty ? property : null); - } - - PrimaryKey AggregatePrimaryKey(IEnumerable primaryKeys) - { - var primarykey = new PrimaryKey(); - var list = new List(); - - foreach (var item in primaryKeys) - { - if (item.IsNonUnique) primarykey.IsNonUnique = true; - if (item.StringComparisonOption != null) primarykey.StringComparisonOption = item.StringComparisonOption; - - list.AddRange(item.Properties); - } - - primarykey.Properties = list.OrderBy(x => x.KeyOrder).ToArray(); - - return primarykey; - } - - // grouped by IndexNo. - SecondaryKey AggregateSecondaryKey(IGrouping secondaryKeys) - { - var secondaryKey = new SecondaryKey(); - secondaryKey.IndexNo = secondaryKeys.Key; - - var list = new List(); - - foreach (var item in secondaryKeys) - { - if (item.IsNonUnique) secondaryKey.IsNonUnique = true; - if (item.StringComparisonOption != null) secondaryKey.StringComparisonOption = item.StringComparisonOption; - - list.AddRange(item.Properties); - } - - secondaryKey.Properties = list.OrderBy(x => x.KeyOrder).ToArray(); - return secondaryKey; - } - - string BuildRecordConstructorFile(AdhocWorkspace workspace, IEnumerable classDeclarations) - { - // using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - - var modify = false; - var editor = new SyntaxEditor(classDeclarations.First().SyntaxTree.GetRoot(), workspace); - foreach (var classDeclaration in classDeclarations) - { - var members = classDeclaration.Members.OfType() - .Where(x => x.Modifiers.Any(y => y.IsKind(SyntaxKind.PublicKeyword))) - .Where(x => - { - foreach (var attr in x.AttributeLists.SelectMany(y => y.Attributes)) - { - var attrName = attr.Name.ToFullString().Trim(); - if (attrName == "IgnoreMember" || attrName == "MessagePack.IgnoreMember") - { - return false; - } - if (attrName == "IgnoreDataMember" || attrName == "System.Runtime.Serialization.IgnoreDataMember") - { - return false; - } - } - return true; - }) - .ToArray(); - - var parameters = ParameterList(SeparatedList(members.Select(x => Parameter(attributeLists: default, modifiers: default, type: x.Type, x.Identifier, @default: null)))); - - var parameterStrings = parameters.Parameters.Select(x => x.Type.ToFullStringTrim()).ToArray(); - - // check existing constructor - var matchedConstructor = classDeclaration.Members.OfType() - .Where(x => x.ParameterList.Parameters.Select(y => y.Type.ToFullStringTrim()).SequenceEqual(parameterStrings)) - .ToArray(); - - if (matchedConstructor.Length != 0) - { - continue; - } - - var body = members.Select(x => AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ThisExpression(), IdentifierName(x.Identifier)), - Token(SyntaxKind.EqualsToken), - IdentifierName(x.Identifier))) - .Select(x => ExpressionStatement(x)); - - var recordCtor = ConstructorDeclaration(classDeclaration.Identifier) - .WithModifiers(TokenList(Token(Sy‌​ntaxKind.PublicKeywo‌​rd))) - .WithParameterList(parameters) - .WithBody(Block(body)) - .NormalizeWhitespace() - .WithLeadingTrivia(LineFeed) - .WithTrailingTrivia(LineFeed); - - var newClassDecl = classDeclaration.AddMembers(recordCtor); - - modify = true; - editor.ReplaceNode(classDeclaration, newClassDecl); - } - - if (modify) - { - var newCodeString = Microsoft.CodeAnalysis.Formatting.Formatter.Format(editor.GetChangedRoot(), workspace).ToFullString(); - return newCodeString; - } - else - { - return null; - } - } - - static string AttributeExpressionToString(ExpressionSyntax expression) - { - if (expression is InvocationExpressionSyntax ie) - { - var expr = ie.ArgumentList.Arguments.Last().Expression; - if (expr is MemberAccessExpressionSyntax mae) - { - return mae.Name?.ToString(); - } - else if (expr is IdentifierNameSyntax inx) - { - return inx.Identifier.ValueText; - } - return null; - } - else if (expression is LiteralExpressionSyntax le) - { - return le.Token.ValueText; - } - return null; - } - } - - internal static class Extensions - { - public static string ToFullStringTrim(this SyntaxNode node) - { - return node.ToFullString().Trim(); - } - - public static string ToFullStringTrim(this SyntaxToken token) - { - return token.ToFullString().Trim(); - } - } -} diff --git a/src/MasterMemory.MSBuild.Tasks/MasterMemory.MSBuild.Tasks.csproj b/src/MasterMemory.MSBuild.Tasks/MasterMemory.MSBuild.Tasks.csproj deleted file mode 100644 index d2657c5..0000000 --- a/src/MasterMemory.MSBuild.Tasks/MasterMemory.MSBuild.Tasks.csproj +++ /dev/null @@ -1,54 +0,0 @@ - - - - netstandard2.0 - latest - - - true - tasks - - true - - MasterMemory.MSBuild.Tasks - $(Version) - Cysharp - Cysharp - MSBuild Tasks of MasterMemory Code Generator. - https://github.com/Cysharp/MasterMemory - $(PackageProjectUrl) - git - database, embedded, inmemory, unity - true - - - - - - - - - - - - - - - - - - - - - <_PackageFiles Include="$(OutDir)\**\*.dll" Exclude="$(OutDir)$(TargetFileName)"> - tasks\netstandard2.0\%(RecursiveDir) - false - Content - - - - - diff --git a/src/MasterMemory.MSBuild.Tasks/MasterMemoryGenerator.cs b/src/MasterMemory.MSBuild.Tasks/MasterMemoryGenerator.cs deleted file mode 100644 index 101bd3c..0000000 --- a/src/MasterMemory.MSBuild.Tasks/MasterMemoryGenerator.cs +++ /dev/null @@ -1,38 +0,0 @@ -using MasterMemory.GeneratorCore; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using System; - -namespace MasterMemory.MSBuild.Tasks -{ - public class MasterMemoryGenerator : Task - { - [Required] - public string UsingNamespace { get; set; } - [Required] - public string InputDirectory { get; set; } - [Required] - public string OutputDirectory { get; set; } - - public string PrefixClassName { get; set; } - - public bool AddImmutableConstructor { get; set; } - public bool ReturnNullIfKeyNotFound { get; set; } = true; - - public bool ForceOverwrite { get; set; } - - public override bool Execute() - { - try - { - new CodeGenerator().GenerateFile(UsingNamespace, InputDirectory, OutputDirectory, PrefixClassName, AddImmutableConstructor, !ReturnNullIfKeyNotFound, ForceOverwrite, x => this.Log.LogMessage(x)); - } - catch (Exception ex) - { - this.Log.LogErrorFromException(ex, true); - return false; - } - return true; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.MSBuild.Tasks/build/MasterMemory.MSBuild.Tasks.props b/src/MasterMemory.MSBuild.Tasks/build/MasterMemory.MSBuild.Tasks.props deleted file mode 100644 index beb5bb6..0000000 --- a/src/MasterMemory.MSBuild.Tasks/build/MasterMemory.MSBuild.Tasks.props +++ /dev/null @@ -1,9 +0,0 @@ - - - - <_MasterMemoryGeneratorTaskFolder>netstandard2.0 - <_MasterMemoryGeneratorTaskAssembly>$(MSBuildThisFileDirectory)..\tasks\$(_MasterMemoryGeneratorTaskFolder)\MasterMemory.MSBuild.Tasks.dll - - - - \ No newline at end of file diff --git a/src/MasterMemory.SourceGenerator/DiagnosticDescriptors.cs b/src/MasterMemory.SourceGenerator/DiagnosticDescriptors.cs new file mode 100644 index 0000000..8c7e326 --- /dev/null +++ b/src/MasterMemory.SourceGenerator/DiagnosticDescriptors.cs @@ -0,0 +1,84 @@ +using Microsoft.CodeAnalysis; +using System; +using System.Collections.Generic; +using System.Text; + +namespace MasterMemory; + +internal sealed class DiagnosticReporter : IEquatable +{ + List? diagnostics; + + public bool HasDiagnostics => diagnostics != null && diagnostics.Count != 0; + + public void ReportDiagnostic(DiagnosticDescriptor diagnosticDescriptor, Location location, params object?[]? messageArgs) + { + var diagnostic = Diagnostic.Create(diagnosticDescriptor, location, messageArgs); + if (diagnostics == null) + { + diagnostics = new(); + } + diagnostics.Add(diagnostic); + } + + public void ReportToContext(SourceProductionContext context) + { + if (diagnostics != null) + { + foreach (var item in diagnostics) + { + context.ReportDiagnostic(item); + } + } + } + + public bool Equals(DiagnosticReporter other) + { + // if error, always false and otherwise ignore + if (diagnostics == null && other.diagnostics == null) + { + return true; + } + + return false; + } +} + +internal static class DiagnosticDescriptors +{ + const string Category = "GenerateMasterMemory"; + + public static void ReportDiagnostic(this SourceProductionContext context, DiagnosticDescriptor diagnosticDescriptor, Location location, params object?[]? messageArgs) + { + var diagnostic = Diagnostic.Create(diagnosticDescriptor, location, messageArgs); + context.ReportDiagnostic(diagnostic); + } + + public static DiagnosticDescriptor Create(int id, string message) + { + return Create(id, message, message); + } + + public static DiagnosticDescriptor Create(int id, string title, string messageFormat) + { + return new DiagnosticDescriptor( + id: "MAM" + id.ToString("000"), + title: title, + messageFormat: messageFormat, + category: Category, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + } + + public static DiagnosticDescriptor RequirePrimaryKey { get; } = Create( + 1, + "MemoryTable does not found PrimaryKey property, Type:{0}."); + + public static DiagnosticDescriptor DuplicatePrimaryKey { get; } = Create( + 2, + "Duplicate PrimaryKey:{0}.{1}"); + + public static DiagnosticDescriptor DuplicateSecondaryKey { get; } = Create( + 3, + "Duplicate SecondaryKey, doesn't allow to add multiple attribute in same attribute list:{0}.{1}"); +} diff --git a/src/MasterMemory.SourceGenerator/GeneratorCore/CodeGenerator.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/CodeGenerator.cs new file mode 100644 index 0000000..bff3e50 --- /dev/null +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/CodeGenerator.cs @@ -0,0 +1,240 @@ +#nullable disable + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace MasterMemory.GeneratorCore +{ + internal static class CodeGenerator + { + // return GenerationContext? + public static GenerationContext CreateGenerationContext(TypeDeclarationSyntax classDecl, AttributeData memoryTableAttribute, DiagnosticReporter reporter) + { + var context = new GenerationContext(); + + context.ClassName = classDecl.Identifier.ToFullString().Trim(); + context.MemoryTableName = memoryTableAttribute.ConstructorArguments[0].Value as string ?? context.ClassName; + + var hasError = false; + var members = classDecl.Members.OfType() + .Select(x => + { + var prop = ExtractPropertyAttribute(x, reporter); + if (prop == null) + { + hasError = true; + return default!; + } + return prop.Value; + }) + .ToArray(); + if (hasError) return null; + + var primaryKey = AggregatePrimaryKey(members.Where(x => x.Item1 != null).Select(x => x.Item1)); + if (primaryKey.Properties.Length == 0) + { + reporter.ReportDiagnostic(DiagnosticDescriptors.RequirePrimaryKey, classDecl.Identifier.GetLocation(), context.ClassName); + return null; + } + + var secondaryKeys = members.SelectMany(x => x.Item2).GroupBy(x => x.IndexNo).Select(x => AggregateSecondaryKey(x)).ToArray(); + var properties = members.Where(x => x.Item3 != null).Select(x => new Property + { + Type = x.Item3.Type.ToFullStringTrim(), + Name = x.Item3.Identifier.Text, + }).ToArray(); + + var root = classDecl.SyntaxTree.GetRoot(); + + var ns = root.DescendantNodes().OfType() + .Select(x => "using " + x.Name.ToFullStringTrim() + ";") + .ToArray(); + + var usingStrings = root.DescendantNodes() + .OfType() + .Select(x => x.ToFullString().Trim()) + .Concat(new[] { "using MasterMemory", "using MasterMemory.Validation", "using System", "using System.Collections.Generic" }) + .Concat(ns) + .Select(x => x.Trim(';') + ";") + .Distinct() + .OrderBy(x => x, StringComparer.Ordinal) + .ToArray(); + + context.PrimaryKey = primaryKey; + context.SecondaryKeys = secondaryKeys; + context.Properties = properties; + context.UsingStrings = usingStrings; + context.OriginalClassDeclaration = classDecl; + return context; + } + + + static (PrimaryKey, List, PropertyDeclarationSyntax)? ExtractPropertyAttribute(PropertyDeclarationSyntax property, DiagnosticReporter reporter) + { + // Attribute Parterns: + // Primarykey(keyOrder = 0) + // SecondaryKey(indexNo, keyOrder = 0) + // NonUnique + // StringComparisonOption + + PrimaryKey resultPrimaryKey = default; + List secondaryKeys = new List(); + bool isSerializableProperty = true; + + foreach (var attrList in property.AttributeLists) + { + var hasNonUnique = false; + PrimaryKey primaryKey = default; + SecondaryKey secondaryKey = default; + + foreach (var attr in attrList.Attributes) + { + var attrName = attr.Name.ToFullString().Trim(); + if (attrName == "PrimaryKey" || attrName == "MasterMemory.Annotations.PrimaryKey") + { + if (resultPrimaryKey != null) + { + // PrimaryKey is AllowMultiple:false so this code is dead + reporter.ReportDiagnostic(DiagnosticDescriptors.DuplicatePrimaryKey, property.Identifier.GetLocation(), property.Type.ToFullString(), property.Identifier.ToFullString()); + return null; + } + + primaryKey = new PrimaryKey(); + var keyProperty = new KeyProperty() + { + Name = property.Identifier.ToFullStringTrim(), + TypeName = property.Type.ToFullStringTrim() + }; + + foreach (var arg in attr.ArgumentList?.Arguments ?? default) + { + keyProperty.KeyOrder = (int)((arg.Expression as LiteralExpressionSyntax).Token.Value); + } + + primaryKey.Properties = new[] { keyProperty }; + } + else if (attrName == "SecondaryKey" || attrName == "MasterMemory.Annotations.SecondaryKey") + { + if (secondaryKey != null) + { + reporter.ReportDiagnostic(DiagnosticDescriptors.DuplicateSecondaryKey, property.Identifier.GetLocation(), property.Type.ToFullString(), property.Identifier.ToFullString()); + return null; + } + + secondaryKey = new SecondaryKey(); + var keyProperty = new KeyProperty() + { + Name = property.Identifier.ToFullStringTrim(), + TypeName = property.Type.ToFullStringTrim() + }; + + var args = attr.ArgumentList.Arguments; + secondaryKey.IndexNo = (int)((args[0].Expression as LiteralExpressionSyntax).Token.Value); + if (args.Count == 2) + { + keyProperty.KeyOrder = (int)((args[1].Expression as LiteralExpressionSyntax).Token.Value); + } + secondaryKey.Properties = new[] { keyProperty }; + } + else if (attrName == "NonUnique" || attrName == "MasterMemory.Annotations.NonUnique") + { + hasNonUnique = true; + } + else if (attrName == "StringComparisonOption" || attrName == "MasterMemory.Annotations.StringComparisonOption") + { + var option = (attr.ArgumentList.Arguments[0].Expression as MemberAccessExpressionSyntax).ToFullStringTrim(); + if (primaryKey != null) + { + primaryKey.StringComparisonOption = option; + } + if (secondaryKey != null) + { + secondaryKey.StringComparisonOption = option; + } + } + else if (!property.Modifiers.Any(SyntaxKind.PublicKeyword) + || attrName == "IgnoreMember" || attrName == "MessagePack.IgnoreMember" + || attrName == "IgnoreDataMember" || attrName == "System.Runtime.Serialization.IgnoreDataMember") + { + isSerializableProperty = false; + } + } + + if (hasNonUnique) + { + if (primaryKey != null) + { + primaryKey.IsNonUnique = true; + } + if (secondaryKey != null) + { + secondaryKey.IsNonUnique = true; + } + } + + if (primaryKey != null) + { + resultPrimaryKey = primaryKey; + } + if (secondaryKey != null) + { + secondaryKeys.Add(secondaryKey); + } + } + + return (resultPrimaryKey, secondaryKeys, isSerializableProperty ? property : null); + } + + static PrimaryKey AggregatePrimaryKey(IEnumerable primaryKeys) + { + var primarykey = new PrimaryKey(); + var list = new List(); + + foreach (var item in primaryKeys) + { + if (item.IsNonUnique) primarykey.IsNonUnique = true; + if (item.StringComparisonOption != null) primarykey.StringComparisonOption = item.StringComparisonOption; + + list.AddRange(item.Properties); + } + + primarykey.Properties = list.OrderBy(x => x.KeyOrder).ToArray(); + + return primarykey; + } + + // grouped by IndexNo. + static SecondaryKey AggregateSecondaryKey(IGrouping secondaryKeys) + { + var secondaryKey = new SecondaryKey(); + secondaryKey.IndexNo = secondaryKeys.Key; + + var list = new List(); + + foreach (var item in secondaryKeys) + { + if (item.IsNonUnique) secondaryKey.IsNonUnique = true; + if (item.StringComparisonOption != null) secondaryKey.StringComparisonOption = item.StringComparisonOption; + + list.AddRange(item.Properties); + } + + secondaryKey.Properties = list.OrderBy(x => x.KeyOrder).ToArray(); + return secondaryKey; + } + } + + internal static class Extensions + { + public static string ToFullStringTrim(this SyntaxNode node) + { + return node.ToFullString().Trim(); + } + + public static string ToFullStringTrim(this SyntaxToken token) + { + return token.ToFullString().Trim(); + } + } +} diff --git a/src/MasterMemory.GeneratorCore/DatabaseBuilderTemplate.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/DatabaseBuilderTemplate.cs similarity index 95% rename from src/MasterMemory.GeneratorCore/DatabaseBuilderTemplate.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/DatabaseBuilderTemplate.cs index ad05c26..b3b1e82 100644 --- a/src/MasterMemory.GeneratorCore/DatabaseBuilderTemplate.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/DatabaseBuilderTemplate.cs @@ -1,10 +1,10 @@ // ------------------------------------------------------------------------------ // -// このコードはツールによって生成されました。 -// ランタイム バージョン: 16.0.0.0 +// This code was generated by a tool. +// Runtime Version: 17.0.0.0 // -// このファイルへの変更は、正しくない動作の原因になる可能性があり、 -// コードが再生成されると失われます。 +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. // // ------------------------------------------------------------------------------ namespace MasterMemory.GeneratorCore @@ -17,7 +17,7 @@ namespace MasterMemory.GeneratorCore /// /// Class to produce the template output /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class DatabaseBuilderTemplate : DatabaseBuilderTemplateBase { /// @@ -25,7 +25,7 @@ public partial class DatabaseBuilderTemplate : DatabaseBuilderTemplateBase /// public virtual string TransformText() { - this.Write("// \r\n#pragma warning disable CS0105\r\n"); + this.Write("// \r\n#nullable enable\r\n#pragma warning disable CS0105\r\n\r\n"); this.Write(this.ToStringHelper.ToStringWithCulture(Using)); this.Write("\r\n\r\nnamespace "); this.Write(this.ToStringHelper.ToStringWithCulture(Namespace)); @@ -35,7 +35,7 @@ public virtual string TransformText() this.Write(this.ToStringHelper.ToStringWithCulture(ClassName)); this.Write("() : this(null) { }\r\n public "); this.Write(this.ToStringHelper.ToStringWithCulture(ClassName)); - this.Write("(MessagePack.IFormatterResolver resolver) : base(resolver) { }\r\n\r\n"); + this.Write("(MessagePack.IFormatterResolver? resolver) : base(resolver) { }\r\n\r\n"); foreach(var item in GenerationContexts) { this.Write(" public "); this.Write(this.ToStringHelper.ToStringWithCulture(ClassName)); @@ -55,7 +55,7 @@ public virtual string TransformText() /// /// Base class for this transformation /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public class DatabaseBuilderTemplateBase { #region Fields @@ -70,7 +70,7 @@ public class DatabaseBuilderTemplateBase /// /// The string builder that generation-time code is using to assemble generated output /// - protected System.Text.StringBuilder GenerationEnvironment + public System.Text.StringBuilder GenerationEnvironment { get { diff --git a/src/MasterMemory.GeneratorCore/DatabaseBuilderTemplate.tt b/src/MasterMemory.SourceGenerator/GeneratorCore/DatabaseBuilderTemplate.tt similarity index 87% rename from src/MasterMemory.GeneratorCore/DatabaseBuilderTemplate.tt rename to src/MasterMemory.SourceGenerator/GeneratorCore/DatabaseBuilderTemplate.tt index d4b24cc..c153e20 100644 --- a/src/MasterMemory.GeneratorCore/DatabaseBuilderTemplate.tt +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/DatabaseBuilderTemplate.tt @@ -4,7 +4,9 @@ <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> // +#nullable enable #pragma warning disable CS0105 + <#= Using #> namespace <#= Namespace #> @@ -12,7 +14,7 @@ namespace <#= Namespace #> public sealed class <#= ClassName #> : DatabaseBuilderBase { public <#= ClassName #>() : this(null) { } - public <#= ClassName #>(MessagePack.IFormatterResolver resolver) : base(resolver) { } + public <#= ClassName #>(MessagePack.IFormatterResolver? resolver) : base(resolver) { } <# foreach(var item in GenerationContexts) { #> public <#= ClassName #> Append(System.Collections.Generic.IEnumerable<<#= item.ClassName #>> dataSource) diff --git a/src/MasterMemory.GeneratorCore/GenerationContext.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/GenerationContext.cs similarity index 85% rename from src/MasterMemory.GeneratorCore/GenerationContext.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/GenerationContext.cs index 6498c3d..ed6398c 100644 --- a/src/MasterMemory.GeneratorCore/GenerationContext.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/GenerationContext.cs @@ -1,36 +1,37 @@ -using Microsoft.CodeAnalysis.CSharp.Syntax; +#nullable disable + +using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Linq; namespace MasterMemory.GeneratorCore { - public class GenerationContext + public record GenerationContext { public string ClassName { get; set; } public string MemoryTableName { get; set; } - public string[] UsingStrings { get; set; } + public EquatableArray UsingStrings { get; set; } public PrimaryKey PrimaryKey { get; set; } - public SecondaryKey[] SecondaryKeys { get; set; } - - public string InputFilePath { get; set; } - public ClassDeclarationSyntax OriginalClassDeclaration { get; set; } + public EquatableArray SecondaryKeys { get; set; } - public Property[] Properties { get; set; } - public KeyBase[] Keys => new KeyBase[] { PrimaryKey }.Concat(SecondaryKeys).ToArray(); + // public string InputFilePath { get; set; } + public IgnoreEquality OriginalClassDeclaration { get; set; } + public EquatableArray Properties { get; set; } + public EquatableArray Keys => new KeyBase[] { PrimaryKey }.Concat(SecondaryKeys).ToArray(); } - public class Property + public record Property { public string Type { get; set; } public string Name { get; set; } } - public abstract class KeyBase + public abstract record KeyBase { public bool IsNonUnique { get; set; } public string StringComparisonOption { get; set; } - public KeyProperty[] Properties { get; set; } + public EquatableArray Properties { get; set; } public abstract string SelectorName { get; } public abstract string TableName { get; } public abstract bool IsPrimary { get; } @@ -93,6 +94,11 @@ public string BuildReturnTypeName(string elementName) return IsNonUnique ? "RangeView<" + elementName + ">" : elementName; } + public string BuildReturnTypeNameForClosest(string elementName) + { + return IsNonUnique ? "RangeView<" + elementName + ">" : elementName + "?"; + } + public string BuildComparer() { if (!IsStringType) @@ -196,14 +202,14 @@ public bool CanInlineBinarySearch } } - public class PrimaryKey : KeyBase + public record PrimaryKey : KeyBase { public override string SelectorName => "primaryIndexSelector"; public override string TableName => "data"; public override bool IsPrimary => true; } - public class SecondaryKey : KeyBase + public record SecondaryKey : KeyBase { public int IndexNo { get; set; } public override string SelectorName => $"secondaryIndex{IndexNo}Selector"; @@ -211,7 +217,7 @@ public class SecondaryKey : KeyBase public override bool IsPrimary => false; } - public class KeyProperty + public record KeyProperty { public int KeyOrder { get; set; } public string Name { get; set; } diff --git a/src/MasterMemory.GeneratorCore/ImmutableBuilderTemplate.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/ImmutableBuilderTemplate.cs similarity index 97% rename from src/MasterMemory.GeneratorCore/ImmutableBuilderTemplate.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/ImmutableBuilderTemplate.cs index f459144..b13d513 100644 --- a/src/MasterMemory.GeneratorCore/ImmutableBuilderTemplate.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/ImmutableBuilderTemplate.cs @@ -1,10 +1,10 @@ // ------------------------------------------------------------------------------ // -// このコードはツールによって生成されました。 -// ランタイム バージョン: 16.0.0.0 +// This code was generated by a tool. +// Runtime Version: 17.0.0.0 // -// このファイルへの変更は、正しくない動作の原因になる可能性があり、 -// コードが再生成されると失われます。 +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. // // ------------------------------------------------------------------------------ namespace MasterMemory.GeneratorCore @@ -17,7 +17,7 @@ namespace MasterMemory.GeneratorCore /// /// Class to produce the template output /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class ImmutableBuilderTemplate : ImmutableBuilderTemplateBase { /// @@ -25,7 +25,7 @@ public partial class ImmutableBuilderTemplate : ImmutableBuilderTemplateBase /// public virtual string TransformText() { - this.Write("// \r\n#pragma warning disable CS0105\r\n"); + this.Write("// \r\n#nullable enable\r\n#pragma warning disable CS0105\r\n\r\n"); this.Write(this.ToStringHelper.ToStringWithCulture(Using)); this.Write("\r\n\r\nnamespace "); this.Write(this.ToStringHelper.ToStringWithCulture(Namespace)); @@ -121,7 +121,7 @@ public virtual string TransformText() /// /// Base class for this transformation /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public class ImmutableBuilderTemplateBase { #region Fields @@ -136,7 +136,7 @@ public class ImmutableBuilderTemplateBase /// /// The string builder that generation-time code is using to assemble generated output /// - protected System.Text.StringBuilder GenerationEnvironment + public System.Text.StringBuilder GenerationEnvironment { get { diff --git a/src/MasterMemory.GeneratorCore/ImmutableBuilderTemplate.tt b/src/MasterMemory.SourceGenerator/GeneratorCore/ImmutableBuilderTemplate.tt similarity index 99% rename from src/MasterMemory.GeneratorCore/ImmutableBuilderTemplate.tt rename to src/MasterMemory.SourceGenerator/GeneratorCore/ImmutableBuilderTemplate.tt index 4ef5a1d..2dc4712 100644 --- a/src/MasterMemory.GeneratorCore/ImmutableBuilderTemplate.tt +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/ImmutableBuilderTemplate.tt @@ -4,7 +4,9 @@ <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> // +#nullable enable #pragma warning disable CS0105 + <#= Using #> namespace <#= Namespace #> diff --git a/src/MasterMemory.GeneratorCore/MemoryDatabaseTemplate.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/MemoryDatabaseTemplate.cs similarity index 97% rename from src/MasterMemory.GeneratorCore/MemoryDatabaseTemplate.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/MemoryDatabaseTemplate.cs index 0398c78..3472d05 100644 --- a/src/MasterMemory.GeneratorCore/MemoryDatabaseTemplate.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/MemoryDatabaseTemplate.cs @@ -25,7 +25,7 @@ public partial class MemoryDatabaseTemplate : MemoryDatabaseTemplateBase /// public virtual string TransformText() { - this.Write("// \r\n#pragma warning disable CS0105\r\n"); + this.Write("// \r\n\r\n#nullable enable\r\n#pragma warning disable CS0105\r\n\r\n"); this.Write(this.ToStringHelper.ToStringWithCulture(Using)); this.Write("\r\n\r\nnamespace "); this.Write(this.ToStringHelper.ToStringWithCulture(Namespace)); @@ -37,7 +37,7 @@ public virtual string TransformText() this.Write(this.ToStringHelper.ToStringWithCulture(item.ClassName)); this.Write("Table "); this.Write(this.ToStringHelper.ToStringWithCulture(item.ClassName)); - this.Write("Table { get; private set; }\r\n"); + this.Write("Table { get; private set; } = default!;\r\n"); } this.Write("\r\n public "); this.Write(this.ToStringHelper.ToStringWithCulture(ClassName)); @@ -61,14 +61,14 @@ public virtual string TransformText() } this.Write(" }\r\n\r\n public "); this.Write(this.ToStringHelper.ToStringWithCulture(ClassName)); - this.Write(@"(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) + this.Write(@"(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver? formatterResolver = null, int maxDegreeOfParallelism = 1) : base(databaseBinary, internString, formatterResolver, maxDegreeOfParallelism) { } protected override void Init(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) { - if(maxDegreeOfParallelism == 1) + if (maxDegreeOfParallelism == 1) { InitSequential(header, databaseBinary, options, maxDegreeOfParallelism); } @@ -172,7 +172,7 @@ public ValidateResult Validate() this.Write("Table.PrimaryKeySelector, result);\r\n"); } this.Write("\r\n return result;\r\n }\r\n\r\n#endif\r\n\r\n static MasterMemory." + - "Meta.MetaDatabase metaTable;\r\n\r\n public static object GetTable("); + "Meta.MetaDatabase? metaTable;\r\n\r\n public static object? GetTable("); this.Write(this.ToStringHelper.ToStringWithCulture(ClassName)); this.Write(" db, string tableName)\r\n {\r\n switch (tableName)\r\n {\r" + "\n"); @@ -230,7 +230,7 @@ public class MemoryDatabaseTemplateBase /// /// The string builder that generation-time code is using to assemble generated output /// - protected System.Text.StringBuilder GenerationEnvironment + public System.Text.StringBuilder GenerationEnvironment { get { diff --git a/src/MasterMemory.GeneratorCore/MemoryDatabaseTemplate.tt b/src/MasterMemory.SourceGenerator/GeneratorCore/MemoryDatabaseTemplate.tt similarity index 93% rename from src/MasterMemory.GeneratorCore/MemoryDatabaseTemplate.tt rename to src/MasterMemory.SourceGenerator/GeneratorCore/MemoryDatabaseTemplate.tt index b2ee6a7..4776a7c 100644 --- a/src/MasterMemory.GeneratorCore/MemoryDatabaseTemplate.tt +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/MemoryDatabaseTemplate.tt @@ -4,7 +4,10 @@ <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> // + +#nullable enable #pragma warning disable CS0105 + <#= Using #> namespace <#= Namespace #> @@ -12,7 +15,7 @@ namespace <#= Namespace #> public sealed class <#= ClassName #> : MemoryDatabaseBase { <# foreach(var item in GenerationContexts) { #> - public <#= item.ClassName #>Table <#= item.ClassName #>Table { get; private set; } + public <#= item.ClassName #>Table <#= item.ClassName #>Table { get; private set; } = default!; <# } #> public <#= ClassName #>( @@ -26,14 +29,14 @@ namespace <#= Namespace #> <# } #> } - public <#= ClassName #>(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) + public <#= ClassName #>(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver? formatterResolver = null, int maxDegreeOfParallelism = 1) : base(databaseBinary, internString, formatterResolver, maxDegreeOfParallelism) { } protected override void Init(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) { - if(maxDegreeOfParallelism == 1) + if (maxDegreeOfParallelism == 1) { InitSequential(header, databaseBinary, options, maxDegreeOfParallelism); } @@ -110,9 +113,9 @@ namespace <#= Namespace #> #endif - static MasterMemory.Meta.MetaDatabase metaTable; + static MasterMemory.Meta.MetaDatabase? metaTable; - public static object GetTable(<#= ClassName #> db, string tableName) + public static object? GetTable(<#= ClassName #> db, string tableName) { switch (tableName) { diff --git a/src/MasterMemory.GeneratorCore/MessagePackResolverTemplate.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/MessagePackResolverTemplate.cs similarity index 94% rename from src/MasterMemory.GeneratorCore/MessagePackResolverTemplate.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/MessagePackResolverTemplate.cs index a4099b7..64c08b3 100644 --- a/src/MasterMemory.GeneratorCore/MessagePackResolverTemplate.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/MessagePackResolverTemplate.cs @@ -1,10 +1,10 @@ // ------------------------------------------------------------------------------ // -// このコードはツールによって生成されました。 -// ランタイム バージョン: 16.0.0.0 +// This code was generated by a tool. +// Runtime Version: 17.0.0.0 // -// このファイルへの変更は、正しくない動作の原因になる可能性があり、 -// コードが再生成されると失われます。 +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. // // ------------------------------------------------------------------------------ namespace MasterMemory.GeneratorCore @@ -17,7 +17,7 @@ namespace MasterMemory.GeneratorCore /// /// Class to produce the template output /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public partial class MessagePackResolverTemplate : MessagePackResolverTemplateBase { /// @@ -25,7 +25,7 @@ public partial class MessagePackResolverTemplate : MessagePackResolverTemplateBa /// public virtual string TransformText() { - this.Write("// \r\n#pragma warning disable CS0105\r\n"); + this.Write("// \r\n#nullable enable\r\n#pragma warning disable CS0105\r\n\r\n"); this.Write(this.ToStringHelper.ToStringWithCulture(Using)); this.Write("\r\n\r\nnamespace "); this.Write(this.ToStringHelper.ToStringWithCulture(Namespace)); @@ -41,14 +41,14 @@ public virtual string TransformText() } - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() + public global::MessagePack.Formatters.IMessagePackFormatter? GetFormatter() { return FormatterCache.formatter; } static class FormatterCache { - public static readonly global::MessagePack.Formatters.IMessagePackFormatter formatter; + public static readonly global::MessagePack.Formatters.IMessagePackFormatter? formatter; static FormatterCache() { @@ -79,9 +79,9 @@ internal static class "); this.Write(this.ToStringHelper.ToStringWithCulture(i)); this.Write(" },\r\n"); } - this.Write(" };\r\n }\r\n\r\n internal static object GetFormatter(Type t)\r" + - "\n {\r\n int key;\r\n if (!lookup.TryGetValue(t, out key" + - ")) return null;\r\n\r\n switch (key)\r\n {\r\n"); + this.Write(" };\r\n }\r\n\r\n internal static object? GetFormatter(Type t)" + + "\r\n {\r\n int key;\r\n if (!lookup.TryGetValue(t, out ke" + + "y)) return null;\r\n\r\n switch (key)\r\n {\r\n"); for(var i = 0; i < GenerationContexts.Length; i++) { var item = GenerationContexts[i]; this.Write(" case "); this.Write(this.ToStringHelper.ToStringWithCulture(i)); @@ -97,7 +97,7 @@ internal static class "); /// /// Base class for this transformation /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] public class MessagePackResolverTemplateBase { #region Fields @@ -112,7 +112,7 @@ public class MessagePackResolverTemplateBase /// /// The string builder that generation-time code is using to assemble generated output /// - protected System.Text.StringBuilder GenerationEnvironment + public System.Text.StringBuilder GenerationEnvironment { get { diff --git a/src/MasterMemory.GeneratorCore/MessagePackResolverTemplate.tt b/src/MasterMemory.SourceGenerator/GeneratorCore/MessagePackResolverTemplate.tt similarity index 93% rename from src/MasterMemory.GeneratorCore/MessagePackResolverTemplate.tt rename to src/MasterMemory.SourceGenerator/GeneratorCore/MessagePackResolverTemplate.tt index a4f041e..59490d9 100644 --- a/src/MasterMemory.GeneratorCore/MessagePackResolverTemplate.tt +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/MessagePackResolverTemplate.tt @@ -4,7 +4,9 @@ <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> // +#nullable enable #pragma warning disable CS0105 + <#= Using #> namespace <#= Namespace #> @@ -18,14 +20,14 @@ namespace <#= Namespace #> } - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() + public global::MessagePack.Formatters.IMessagePackFormatter? GetFormatter() { return FormatterCache.formatter; } static class FormatterCache { - public static readonly global::MessagePack.Formatters.IMessagePackFormatter formatter; + public static readonly global::MessagePack.Formatters.IMessagePackFormatter? formatter; static FormatterCache() { @@ -52,7 +54,7 @@ namespace <#= Namespace #> }; } - internal static object GetFormatter(Type t) + internal static object? GetFormatter(Type t) { int key; if (!lookup.TryGetValue(t, out key)) return null; diff --git a/src/MasterMemory.GeneratorCore/TableTemplate.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/TableTemplate.cs similarity index 98% rename from src/MasterMemory.GeneratorCore/TableTemplate.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/TableTemplate.cs index b61a879..7e5a16d 100644 --- a/src/MasterMemory.GeneratorCore/TableTemplate.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/TableTemplate.cs @@ -25,7 +25,7 @@ public partial class TableTemplate : TableTemplateBase /// public virtual string TransformText() { - this.Write("// \r\n#pragma warning disable CS0105\r\n"); + this.Write("// \r\n\r\n#nullable enable\r\n#pragma warning disable CS0105\r\n\r\n"); this.Write(this.ToStringHelper.ToStringWithCulture(Using)); this.Write("\r\n\r\nnamespace "); this.Write(this.ToStringHelper.ToStringWithCulture(Namespace)); @@ -101,7 +101,7 @@ public virtual string TransformText() if(item.CanInlineBinarySearch) { this.Write(" [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServic" + "es.MethodImplOptions.AggressiveInlining)]\r\n public "); - this.Write(this.ToStringHelper.ToStringWithCulture(item.BuildReturnTypeName(GenerationContext.ClassName))); + this.Write(this.ToStringHelper.ToStringWithCulture(item.BuildReturnTypeName(GenerationContext.ClassName) + (ThrowKeyIfNotFound ? "" : "?"))); this.Write(" FindBy"); this.Write(this.ToStringHelper.ToStringWithCulture(item.BuildMethodName())); this.Write("("); @@ -137,7 +137,7 @@ public virtual string TransformText() if (found < 0) { lo = mid + 1; } else { hi = mid - 1; } } - result = default; + result = default!; return false; } "); @@ -199,7 +199,7 @@ public virtual string TransformText() } } this.Write("\r\n public "); - this.Write(this.ToStringHelper.ToStringWithCulture(item.BuildReturnTypeName(GenerationContext.ClassName))); + this.Write(this.ToStringHelper.ToStringWithCulture(item.BuildReturnTypeNameForClosest(GenerationContext.ClassName))); this.Write(" FindClosestBy"); this.Write(this.ToStringHelper.ToStringWithCulture(item.BuildMethodName())); this.Write("("); @@ -266,7 +266,7 @@ public virtual string TransformText() this.Write(this.ToStringHelper.ToStringWithCulture(GenerationContext.ClassName)); this.Write(").GetProperty(\""); this.Write(this.ToStringHelper.ToStringWithCulture(prop.Name)); - this.Write("\")),\r\n"); + this.Write("\")!),\r\n"); } this.Write(" },\r\n new MasterMemory.Meta.MetaIndex[]{\r\n"); foreach(var key in GenerationContext.Keys) { @@ -277,7 +277,7 @@ public virtual string TransformText() this.Write(this.ToStringHelper.ToStringWithCulture(GenerationContext.ClassName)); this.Write(").GetProperty(\""); this.Write(this.ToStringHelper.ToStringWithCulture(keyProp.Name)); - this.Write("\"),\r\n"); + this.Write("\")!,\r\n"); } this.Write(" }, "); this.Write(this.ToStringHelper.ToStringWithCulture(key.IsPrimary.ToString().ToLower())); @@ -310,7 +310,7 @@ public class TableTemplateBase /// /// The string builder that generation-time code is using to assemble generated output /// - protected System.Text.StringBuilder GenerationEnvironment + public System.Text.StringBuilder GenerationEnvironment { get { diff --git a/src/MasterMemory.GeneratorCore/TableTemplate.tt b/src/MasterMemory.SourceGenerator/GeneratorCore/TableTemplate.tt similarity index 95% rename from src/MasterMemory.GeneratorCore/TableTemplate.tt rename to src/MasterMemory.SourceGenerator/GeneratorCore/TableTemplate.tt index e561375..af6b446 100644 --- a/src/MasterMemory.GeneratorCore/TableTemplate.tt +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/TableTemplate.tt @@ -4,7 +4,10 @@ <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> // + +#nullable enable #pragma warning disable CS0105 + <#= Using #> namespace <#= Namespace #>.Tables @@ -39,7 +42,7 @@ namespace <#= Namespace #>.Tables <# foreach(var item in new KeyBase[] { GenerationContext.PrimaryKey }.Concat(GenerationContext.SecondaryKeys)) { #> <# if(item.CanInlineBinarySearch) { #> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public <#= item.BuildReturnTypeName(GenerationContext.ClassName) #> FindBy<#= item.BuildMethodName() #>(<#= item.BuildTypeName() #> key) + public <#= item.BuildReturnTypeName(GenerationContext.ClassName) + (ThrowKeyIfNotFound ? "" : "?") #> FindBy<#= item.BuildMethodName() #>(<#= item.BuildTypeName() #> key) { var lo = 0; var hi = data.Length - 1; @@ -73,7 +76,7 @@ namespace <#= Namespace #>.Tables if (found < 0) { lo = mid + 1; } else { hi = mid - 1; } } - result = default; + result = default!; return false; } <# } else { #> @@ -95,7 +98,7 @@ namespace <#= Namespace #>.Tables <# } #> <# } #> - public <#= item.BuildReturnTypeName(GenerationContext.ClassName) #> FindClosestBy<#= item.BuildMethodName() #>(<#= item.BuildTypeName() #> key, bool selectLower = true) + public <#= item.BuildReturnTypeNameForClosest(GenerationContext.ClassName) #> FindClosestBy<#= item.BuildMethodName() #>(<#= item.BuildTypeName() #> key, bool selectLower = true) { return <#= item.BuildFindPrefix() #>ClosestCore(<#= item.TableName #>, <#= item.SelectorName #>, <#= item.BuildComparer() #>, key, selectLower); } @@ -131,14 +134,14 @@ namespace <#= Namespace #>.Tables new MasterMemory.Meta.MetaProperty[] { <# foreach(var prop in GenerationContext.Properties) { #> - new MasterMemory.Meta.MetaProperty(typeof(<#= GenerationContext.ClassName #>).GetProperty("<#= prop.Name #>")), + new MasterMemory.Meta.MetaProperty(typeof(<#= GenerationContext.ClassName #>).GetProperty("<#= prop.Name #>")!), <# } #> }, new MasterMemory.Meta.MetaIndex[]{ <# foreach(var key in GenerationContext.Keys) { #> new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { <# foreach(var keyProp in key.Properties) { #> - typeof(<#= GenerationContext.ClassName #>).GetProperty("<#= keyProp.Name #>"), + typeof(<#= GenerationContext.ClassName #>).GetProperty("<#= keyProp.Name #>")!, <# } #> }, <#= key.IsPrimary.ToString().ToLower() #>, <#= (!key.IsNonUnique).ToString().ToLower() #>, <#= key.BuildComparer() #>), <# } #> diff --git a/src/MasterMemory.GeneratorCore/Template.cs b/src/MasterMemory.SourceGenerator/GeneratorCore/Template.cs similarity index 98% rename from src/MasterMemory.GeneratorCore/Template.cs rename to src/MasterMemory.SourceGenerator/GeneratorCore/Template.cs index 6b68214..24322c7 100644 --- a/src/MasterMemory.GeneratorCore/Template.cs +++ b/src/MasterMemory.SourceGenerator/GeneratorCore/Template.cs @@ -1,4 +1,6 @@ -using System; +#nullable disable + +using System; using System.Collections.Generic; using System.Text; diff --git a/src/MasterMemory.GeneratorCore/MasterMemory.GeneratorCore.csproj b/src/MasterMemory.SourceGenerator/MasterMemory.GeneratorCore.csproj similarity index 100% rename from src/MasterMemory.GeneratorCore/MasterMemory.GeneratorCore.csproj rename to src/MasterMemory.SourceGenerator/MasterMemory.GeneratorCore.csproj diff --git a/src/MasterMemory.SourceGenerator/MasterMemory.SourceGenerator.csproj b/src/MasterMemory.SourceGenerator/MasterMemory.SourceGenerator.csproj new file mode 100644 index 0000000..09d46d9 --- /dev/null +++ b/src/MasterMemory.SourceGenerator/MasterMemory.SourceGenerator.csproj @@ -0,0 +1,79 @@ + + + + netstandard2.0 + 13 + enable + enable + true + cs + MasterMemory + + + false + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + TextTemplatingFilePreprocessor + DatabaseBuilderTemplate.cs + + + TextTemplatingFilePreprocessor + ImmutableBuilderTemplate.cs + + + TextTemplatingFilePreprocessor + MemoryDatabaseTemplate.cs + + + TextTemplatingFilePreprocessor + MessagePackResolverTemplate.cs + + + TextTemplatingFilePreprocessor + TableTemplate.cs + + + + + + + + + + True + True + DatabaseBuilderTemplate.tt + + + True + True + ImmutableBuilderTemplate.tt + + + True + True + MemoryDatabaseTemplate.tt + + + True + True + MessagePackResolverTemplate.tt + + + True + True + TableTemplate.tt + + + diff --git a/src/MasterMemory.SourceGenerator/MasterMemoryGenerator.cs b/src/MasterMemory.SourceGenerator/MasterMemoryGenerator.cs new file mode 100644 index 0000000..ef2cb9f --- /dev/null +++ b/src/MasterMemory.SourceGenerator/MasterMemoryGenerator.cs @@ -0,0 +1,126 @@ +using MasterMemory.GeneratorCore; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using System.Diagnostics; + +namespace MasterMemory.SourceGenerator; + +[Generator(LanguageNames.CSharp)] +public partial class MasterMemoryGenerator : IIncrementalGenerator +{ + public void Initialize(IncrementalGeneratorInitializationContext context) + { + context.RegisterPostInitializationOutput(MasterMemoryGeneratorOptions.EmitAttribute); + + var namespaceProvider = context.AnalyzerConfigOptionsProvider.Select((x, _) => + { + x.GlobalOptions.TryGetValue("build_property.RootNamespace", out var defaultNamespace); + return defaultNamespace; + }) + .WithTrackingName("MasterMemory.AnalyzerConfig"); + + var generatorOptions = context.CompilationProvider.Select((compilation, _) => + { + foreach (var attr in compilation.Assembly.GetAttributes()) + { + if (attr.AttributeClass?.Name == "MasterMemoryGeneratorOptionsAttribute") + { + return MasterMemoryGeneratorOptions.FromAttribute(attr); + } + } + + return default; + }) + .WithTrackingName("MasterMemory.CompilationProvider"); + + var memoryTables = context.SyntaxProvider.ForAttributeWithMetadataName("MasterMemory.MemoryTableAttribute", + (node, token) => true, + (ctx, token) => ctx) + .WithTrackingName("MasterMemory.SyntaxProvider.0_ForAttributeWithMetadataName") + .Collect() + .Select((xs, _) => + { + var list = new List(); + var reporter = new DiagnosticReporter(); + foreach (var ctx in xs) + { + var memoryTableAttr = ctx.Attributes[0]; // AllowMultiple=false + var classDecl = ctx.TargetNode as TypeDeclarationSyntax; // class or record + var context = CodeGenerator.CreateGenerationContext(classDecl!, memoryTableAttr, reporter); + if (context != null) + { + list.Add(context); + } + } + list.Sort((a, b) => string.Compare(a.ClassName, b.ClassName, StringComparison.Ordinal)); + return (reporter, new EquatableArray(list.ToArray())); + }) + .WithTrackingName("MasterMemory.SyntaxProvider.1_CollectAndSelect"); + + var allCombined = memoryTables + .Combine(namespaceProvider) + .Combine(generatorOptions) + .WithTrackingName("MasterMemory.SyntaxProvider.2_AllCombined"); + + context.RegisterSourceOutput(allCombined, EmitMemoryTable); + } + + void EmitMemoryTable(SourceProductionContext context, (((DiagnosticReporter, EquatableArray), string?), MasterMemoryGeneratorOptions) value) + { + var (((diagnostic, memoryTables), defaultNamespace), generatorOptions) = value; + diagnostic.ReportToContext(context); + if (memoryTables.Length == 0) + { + return; + } + + var usingNamespace = generatorOptions.Namespace ?? defaultNamespace ?? "MasterMemory"; + var prefixClassName = generatorOptions.PrefixClassName ?? ""; + var throwIfKeyNotFound = !generatorOptions.IsReturnNullIfKeyNotFound; // becareful, reverse! + + var usingStrings = string.Join(Environment.NewLine, memoryTables.SelectMany(x => x.UsingStrings).Distinct().OrderBy(x => x, StringComparer.Ordinal)); + + var builderTemplate = new DatabaseBuilderTemplate(); + var databaseTemplate = new MemoryDatabaseTemplate(); + var immutableBuilderTemplate = new ImmutableBuilderTemplate(); + var resolverTemplate = new MessagePackResolverTemplate(); + builderTemplate.Namespace = databaseTemplate.Namespace = immutableBuilderTemplate.Namespace = resolverTemplate.Namespace = usingNamespace; + builderTemplate.PrefixClassName = databaseTemplate.PrefixClassName = immutableBuilderTemplate.PrefixClassName = resolverTemplate.PrefixClassName = prefixClassName; + builderTemplate.Using = databaseTemplate.Using = immutableBuilderTemplate.Using = resolverTemplate.Using = (usingStrings + Environment.NewLine + ("using " + usingNamespace + ".Tables;")); + builderTemplate.GenerationContexts = databaseTemplate.GenerationContexts = immutableBuilderTemplate.GenerationContexts = resolverTemplate.GenerationContexts = memoryTables.ToArray(); + + Log(AddSource(context, builderTemplate.ClassName, builderTemplate.TransformText())); + Log(AddSource(context, immutableBuilderTemplate.ClassName, immutableBuilderTemplate.TransformText())); + Log(AddSource(context, databaseTemplate.ClassName, databaseTemplate.TransformText())); + Log(AddSource(context, resolverTemplate.ClassName, resolverTemplate.TransformText())); + + foreach (var generationContext in memoryTables) + { + var template = new TableTemplate() + { + Namespace = usingNamespace, + GenerationContext = generationContext, + Using = string.Join(Environment.NewLine, generationContext.UsingStrings), + ThrowKeyIfNotFound = throwIfKeyNotFound + }; + + Log(AddSource(context, generationContext.ClassName + "Table", template.TransformText())); + } + } + + static void Log(string msg) => Trace.WriteLine(msg); + + static string AddSource(SourceProductionContext context, string fileName, string content) + { + var contentString = NormalizeNewLines(content); + context.AddSource($"MasterMemory.{fileName}.g.cs", contentString); + return $"Generate {fileName}."; + + static string NormalizeNewLines(string content) + { + // The T4 generated code may be text with mixed line ending types. (CR + CRLF) + // We need to normalize the line ending type in each Operating Systems. (e.g. Windows=CRLF, Linux/macOS=LF) + return content.Replace("\r\n", "\n").Replace("\n", Environment.NewLine); + } + } +} diff --git a/src/MasterMemory.SourceGenerator/MasterMemoryGeneratorOptions.cs b/src/MasterMemory.SourceGenerator/MasterMemoryGeneratorOptions.cs new file mode 100644 index 0000000..590aca2 --- /dev/null +++ b/src/MasterMemory.SourceGenerator/MasterMemoryGeneratorOptions.cs @@ -0,0 +1,36 @@ +using Microsoft.CodeAnalysis; + +namespace MasterMemory.SourceGenerator; + +readonly record struct MasterMemoryGeneratorOptions(string? Namespace, string PrefixClassName, bool IsReturnNullIfKeyNotFound) +{ + public static MasterMemoryGeneratorOptions FromAttribute(AttributeData attributeData) + { + var args = attributeData.NamedArguments; + + var ns = args.FirstOrDefault(x => x.Key == nameof(Namespace)).Value.Value as string ?? null; + var prefix = args.FirstOrDefault(x => x.Key == nameof(PrefixClassName)).Value.Value as string ?? ""; + var isReturnNull = args.FirstOrDefault(x => x.Key == nameof(IsReturnNullIfKeyNotFound)).Value.Value as bool? ?? null; + + return new MasterMemoryGeneratorOptions(ns, prefix, isReturnNull ?? false); + } + + public static void EmitAttribute(IncrementalGeneratorPostInitializationContext context) + { + context.AddSource("MasterMemory.MasterMemoryGeneratorOptions.cs", """ +#nullable enable +using System; + +namespace MasterMemory +{ + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] + internal sealed class MasterMemoryGeneratorOptionsAttribute : Attribute + { + public string? Namespace { get; set; } = null; + public string PrefixClassName { get; set; } = ""; + public bool IsReturnNullIfKeyNotFound { get; set; } = false; + } +} +"""); + } +} diff --git a/src/MasterMemory.SourceGenerator/Polyfill/System.CodeDom.cs b/src/MasterMemory.SourceGenerator/Polyfill/System.CodeDom.cs new file mode 100644 index 0000000..7aa7a2a --- /dev/null +++ b/src/MasterMemory.SourceGenerator/Polyfill/System.CodeDom.cs @@ -0,0 +1,21 @@ +#nullable disable + +using System; +using System.Collections.Generic; +using System.Text; + +namespace System.CodeDom.Compiler +{ + public class CompilerError + { + public string ErrorText { get; set; } + public bool IsWarning { get; set; } + } + + public class CompilerErrorCollection + { + public void Add(CompilerError error) + { + } + } +} \ No newline at end of file diff --git a/src/MasterMemory.SourceGenerator/Properties/launchSettings.json b/src/MasterMemory.SourceGenerator/Properties/launchSettings.json new file mode 100644 index 0000000..f1f159b --- /dev/null +++ b/src/MasterMemory.SourceGenerator/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "Profile 1": { + "commandName": "DebugRoslynComponent", + "targetProject": "..\\..\\sandbox\\GeneratorSandbox\\GeneratorSandbox.csproj" + } + } +} \ No newline at end of file diff --git a/src/MasterMemory.SourceGenerator/Utility/EquatableArray.cs b/src/MasterMemory.SourceGenerator/Utility/EquatableArray.cs new file mode 100644 index 0000000..c222a71 --- /dev/null +++ b/src/MasterMemory.SourceGenerator/Utility/EquatableArray.cs @@ -0,0 +1,58 @@ +using System.Collections; +using System.Runtime.CompilerServices; + +namespace MasterMemory; + +public readonly struct EquatableArray : IEquatable>, IEnumerable + where T : IEquatable +{ + readonly T[]? array; + + public EquatableArray() // for collection literal [] + { + array = []; + } + + public EquatableArray(T[] array) + { + this.array = array; + } + + public static implicit operator EquatableArray(T[] array) + { + return new EquatableArray(array); + } + + public ref readonly T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref array![index]; + } + + public int Length => array!.Length; + + public ReadOnlySpan AsSpan() + { + return array.AsSpan(); + } + + public ReadOnlySpan.Enumerator GetEnumerator() + { + return AsSpan().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return array.AsEnumerable().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return array.AsEnumerable().GetEnumerator(); + } + + public bool Equals(EquatableArray other) + { + return AsSpan().SequenceEqual(other.AsSpan()); + } +} diff --git a/src/MasterMemory.SourceGenerator/Utility/IgnoreEquality.cs b/src/MasterMemory.SourceGenerator/Utility/IgnoreEquality.cs new file mode 100644 index 0000000..05005a4 --- /dev/null +++ b/src/MasterMemory.SourceGenerator/Utility/IgnoreEquality.cs @@ -0,0 +1,22 @@ +namespace MasterMemory; + +public readonly struct IgnoreEquality(T value) : IEquatable> +{ + public readonly T Value => value; + + public static implicit operator IgnoreEquality(T value) + { + return new IgnoreEquality(value); + } + + public static implicit operator T(IgnoreEquality value) + { + return value.Value; + } + + public bool Equals(IgnoreEquality other) + { + // always true to ignore equality check. + return true; + } +} diff --git a/src/MasterMemory.Unity/Assets/NuGet.config b/src/MasterMemory.Unity/Assets/NuGet.config new file mode 100644 index 0000000..0c08388 --- /dev/null +++ b/src/MasterMemory.Unity/Assets/NuGet.config @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Buffers.dll.meta b/src/MasterMemory.Unity/Assets/NuGet.config.meta similarity index 87% rename from src/MasterMemory.Unity/Assets/Plugins/System.Buffers.dll.meta rename to src/MasterMemory.Unity/Assets/NuGet.config.meta index cfafcc6..2472d55 100644 --- a/src/MasterMemory.Unity/Assets/Plugins/System.Buffers.dll.meta +++ b/src/MasterMemory.Unity/Assets/NuGet.config.meta @@ -1,5 +1,7 @@ fileFormatVersion: 2 -guid: cfed5f4adebd4cc6586d1ffea90646fc +guid: e5322b2ac44bca4478137f3076edc3bb +labels: +- NuGetForUnity PluginImporter: externalObjects: {} serializedVersion: 2 @@ -14,7 +16,7 @@ PluginImporter: - first: Any: second: - enabled: 1 + enabled: 0 settings: {} - first: Editor: Editor @@ -25,9 +27,8 @@ PluginImporter: - first: Windows Store Apps: WindowsStoreApps second: - enabled: 0 - settings: - CPU: AnyCPU + enabled: 1 + settings: {} userData: assetBundleName: assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Plugins.meta b/src/MasterMemory.Unity/Assets/Packages.meta similarity index 77% rename from src/MasterMemory.Unity/Assets/Plugins.meta rename to src/MasterMemory.Unity/Assets/Packages.meta index 1a35453..2526537 100644 --- a/src/MasterMemory.Unity/Assets/Plugins.meta +++ b/src/MasterMemory.Unity/Assets/Packages.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ce17bade98a412e408e2f3a4b7c4a107 +guid: 26358cf27391727439065c2117eb2e52 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Buffers.dll b/src/MasterMemory.Unity/Assets/Plugins/System.Buffers.dll deleted file mode 100644 index b6d9c77..0000000 Binary files a/src/MasterMemory.Unity/Assets/Plugins/System.Buffers.dll and /dev/null differ diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Memory.dll b/src/MasterMemory.Unity/Assets/Plugins/System.Memory.dll deleted file mode 100644 index bdfc501..0000000 Binary files a/src/MasterMemory.Unity/Assets/Plugins/System.Memory.dll and /dev/null differ diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll b/src/MasterMemory.Unity/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll deleted file mode 100644 index 3156239..0000000 Binary files a/src/MasterMemory.Unity/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll and /dev/null differ diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta b/src/MasterMemory.Unity/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta deleted file mode 100644 index bfe10c6..0000000 --- a/src/MasterMemory.Unity/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta +++ /dev/null @@ -1,33 +0,0 @@ -fileFormatVersion: 2 -guid: 1b23775a59c7085cdb02341c16a19ef4 -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 0 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - Any: - second: - enabled: 1 - settings: {} - - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - - first: - Windows Store Apps: WindowsStoreApps - second: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Threading.Tasks.Extensions.dll b/src/MasterMemory.Unity/Assets/Plugins/System.Threading.Tasks.Extensions.dll deleted file mode 100644 index e059050..0000000 Binary files a/src/MasterMemory.Unity/Assets/Plugins/System.Threading.Tasks.Extensions.dll and /dev/null differ diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Threading.Tasks.Extensions.dll.meta b/src/MasterMemory.Unity/Assets/Plugins/System.Threading.Tasks.Extensions.dll.meta deleted file mode 100644 index fe9eaac..0000000 --- a/src/MasterMemory.Unity/Assets/Plugins/System.Threading.Tasks.Extensions.dll.meta +++ /dev/null @@ -1,33 +0,0 @@ -fileFormatVersion: 2 -guid: 79b471354b1f5b597bf692d41ee441a4 -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 0 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - Any: - second: - enabled: 1 - settings: {} - - first: - Editor: Editor - second: - enabled: 0 - settings: - DefaultValueInitialized: true - - first: - Windows Store Apps: WindowsStoreApps - second: - enabled: 0 - settings: - CPU: AnyCPU - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scenes/SampleScene.unity b/src/MasterMemory.Unity/Assets/Scenes/Main.unity similarity index 63% rename from src/MasterMemory.Unity/Assets/Scenes/SampleScene.unity rename to src/MasterMemory.Unity/Assets/Scenes/Main.unity index e5ecd0a..bd1daac 100644 --- a/src/MasterMemory.Unity/Assets/Scenes/SampleScene.unity +++ b/src/MasterMemory.Unity/Assets/Scenes/Main.unity @@ -43,19 +43,18 @@ RenderSettings: --- !u!157 &3 LightmapSettings: m_ObjectHideFlags: 0 - serializedVersion: 11 + serializedVersion: 12 m_GIWorkflowMode: 1 m_GISettings: serializedVersion: 2 m_BounceScale: 1 m_IndirectOutputScale: 1 m_AlbedoBoost: 1 - m_TemporalCoherenceThreshold: 1 m_EnvironmentLightingMode: 0 m_EnableBakedLightmaps: 0 m_EnableRealtimeLightmaps: 0 m_LightmapEditorSettings: - serializedVersion: 10 + serializedVersion: 12 m_Resolution: 2 m_BakeResolution: 40 m_AtlasSize: 1024 @@ -63,6 +62,7 @@ LightmapSettings: m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 @@ -72,15 +72,21 @@ LightmapSettings: m_FinalGatherRayCount: 256 m_ReflectionCompression: 2 m_MixedBakeMode: 2 - m_BakeBackend: 0 + m_BakeBackend: 1 m_PVRSampling: 1 m_PVRDirectSampleCount: 32 - m_PVRSampleCount: 500 + m_PVRSampleCount: 512 m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 - m_PVRFilteringMode: 1 + m_PVREnvironmentMIS: 1 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 @@ -88,15 +94,17 @@ LightmapSettings: m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 - m_ShowResolutionOverlay: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 m_LightingDataAsset: {fileID: 0} - m_UseShadowmask: 1 + m_LightingSettings: {fileID: 0} --- !u!196 &4 NavMeshSettings: serializedVersion: 2 m_ObjectHideFlags: 0 m_BuildSettings: - serializedVersion: 2 + serializedVersion: 3 agentTypeID: 0 agentRadius: 0.5 agentHeight: 2 @@ -109,20 +117,24 @@ NavMeshSettings: cellSize: 0.16666667 manualTileSize: 0 tileSize: 256 - accuratePlacement: 0 + buildHeightMesh: 0 + maxJobWorkers: 0 + preserveTilesOutsideBounds: 0 debug: m_Flags: 0 m_NavMeshData: {fileID: 0} ---- !u!1 &519420028 +--- !u!1 &242466054 GameObject: m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 5 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 m_Component: - - component: {fileID: 519420032} - - component: {fileID: 519420031} - - component: {fileID: 519420029} + - component: {fileID: 242466057} + - component: {fileID: 242466056} + - component: {fileID: 242466055} + - component: {fileID: 242466058} m_Layer: 0 m_Name: Main Camera m_TagString: MainCamera @@ -130,23 +142,39 @@ GameObject: m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 ---- !u!81 &519420029 +--- !u!81 &242466055 AudioListener: m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 519420028} + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 242466054} m_Enabled: 1 ---- !u!20 &519420031 +--- !u!20 &242466056 Camera: m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 519420028} + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 242466054} m_Enabled: 1 serializedVersion: 2 - m_ClearFlags: 2 + m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 + m_Iso: 200 + m_ShutterSpeed: 0.005 + m_Aperture: 16 + m_FocusDistance: 10 + m_FocalLength: 50 + m_BladeCount: 5 + m_Curvature: {x: 2, y: 11} + m_BarrelClipping: 0.25 + m_Anamorphism: 0 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 @@ -165,24 +193,43 @@ Camera: m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 - m_TargetEye: 0 + m_TargetEye: 3 m_HDR: 1 - m_AllowMSAA: 0 + m_AllowMSAA: 1 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 - m_OcclusionCulling: 0 + m_OcclusionCulling: 1 m_StereoConvergence: 10 m_StereoSeparation: 0.022 ---- !u!4 &519420032 +--- !u!4 &242466057 Transform: m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 519420028} + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 242466054} + serializedVersion: 2 m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: -10} m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &242466058 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 242466054} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a7e2d905f1c43ee42914ee6de131c41e, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1660057539 &9223372036854775807 +SceneRoots: + m_ObjectHideFlags: 0 + m_Roots: + - {fileID: 242466057} diff --git a/src/MasterMemory.Unity/Assets/Scenes/SampleScene.unity.meta b/src/MasterMemory.Unity/Assets/Scenes/Main.unity.meta similarity index 74% rename from src/MasterMemory.Unity/Assets/Scenes/SampleScene.unity.meta rename to src/MasterMemory.Unity/Assets/Scenes/Main.unity.meta index c1e3c88..e569677 100644 --- a/src/MasterMemory.Unity/Assets/Scenes/SampleScene.unity.meta +++ b/src/MasterMemory.Unity/Assets/Scenes/Main.unity.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2cda990e2423bbf4892e6590ba056729 +guid: d5ed035d1a1185e43a6e9d45e3d68f1f DefaultImporter: externalObjects: {} userData: diff --git a/src/MasterMemory.Unity/Assets/Scripts/Editor.meta b/src/MasterMemory.Unity/Assets/Scripts/Editor.meta deleted file mode 100644 index 2d3cc5b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/Editor.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c46767cc8d723d649ab6aaaeb1d72c12 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/Editor/PackageExporter.cs b/src/MasterMemory.Unity/Assets/Scripts/Editor/PackageExporter.cs deleted file mode 100644 index 60a878a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/Editor/PackageExporter.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEngine; - -public static class PackageExporter -{ - [MenuItem("Tools/Export Unitypackage")] - public static void Export() - { - var root = "Scripts/MasterMemory"; - var version = GetVersion(root); - - var fileName = string.IsNullOrEmpty(version) ? "MasterMemory.Unity.unitypackage" : $"MasterMemory.Unity.{version}.unitypackage"; - var exportPath = "./" + fileName; - - var path = Path.Combine(Application.dataPath, root); - var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) - .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta") - .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) - .ToArray(); - - UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, assets)); - - AssetDatabase.ExportPackage( - assets, - exportPath, - ExportPackageOptions.Default); - - UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath)); - } - - static string GetVersion(string root) - { - var version = Environment.GetEnvironmentVariable("UNITY_PACKAGE_VERSION"); - var versionJson = Path.Combine(Application.dataPath, root, "package.json"); - - if (File.Exists(versionJson)) - { - var v = JsonUtility.FromJson(File.ReadAllText(versionJson)); - - if (!string.IsNullOrEmpty(version)) - { - if (v.version != version) - { - var msg = $"package.json and env version are mismatched. UNITY_PACKAGE_VERSION:{version}, package.json:{v.version}"; - - if (Application.isBatchMode) - { - Console.WriteLine(msg); - Application.Quit(1); - } - - throw new Exception("package.json and env version are mismatched."); - } - } - - version = v.version; - } - - return version; - } - - public class Version - { - public string version; - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/Editor/PackageExporter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/Editor/PackageExporter.cs.meta deleted file mode 100644 index 63bc389..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/Editor/PackageExporter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0104ef67be3b9ca498ff698ad4e0bd71 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory.meta deleted file mode 100644 index de5933b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 5dcaecddcbde0ca4f837b33c0d083f04 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations.meta deleted file mode 100644 index 39fb8b6..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 8d6094c9ffd523141aa6afcd16abb40e -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations/Attributes.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations/Attributes.cs deleted file mode 100644 index 71967d1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations/Attributes.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; - -namespace MasterMemory -{ - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class MemoryTableAttribute : Attribute - { - public string TableName { get; } - - public MemoryTableAttribute(string tableName) - { - this.TableName = tableName; - } - } - - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class PrimaryKeyAttribute : Attribute - { - public int KeyOrder { get; } - - public PrimaryKeyAttribute(int keyOrder = 0) - { - this.KeyOrder = keyOrder; - } - } - - [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] - public class SecondaryKeyAttribute : Attribute - { - public int IndexNo { get; } - public int KeyOrder { get; } - - public SecondaryKeyAttribute(int indexNo, int keyOrder = 0) - { - this.IndexNo = indexNo; - this.KeyOrder = keyOrder; - } - } - - [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] - public class NonUniqueAttribute : Attribute - { - - } - - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class StringComparisonOptionAttribute : Attribute - { - public StringComparison StringComparison { get; } - - public StringComparisonOptionAttribute(StringComparison stringComparison) - { - this.StringComparison = stringComparison; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBase.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBase.cs deleted file mode 100644 index a1b1429..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBase.cs +++ /dev/null @@ -1,113 +0,0 @@ -using MasterMemory.Internal; -using MessagePack; -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; - -namespace MasterMemory -{ - public abstract class DatabaseBuilderBase - { - readonly ByteBufferWriter bufferWriter = new ByteBufferWriter(); - - // TableName, (Offset, Count) - readonly Dictionary header = new Dictionary(); - readonly MessagePackSerializerOptions options; - - public DatabaseBuilderBase(MessagePackSerializerOptions options) - { - // options keep null to lazily use default options - if (options != null) - { - options = options.WithCompression(MessagePackCompression.Lz4Block); - } - } - - public DatabaseBuilderBase(IFormatterResolver resolver) - { - if (resolver != null) - { - this.options = MessagePackSerializer.DefaultOptions - .WithCompression(MessagePackCompression.Lz4Block) - .WithResolver(resolver); - } - - } - - protected void AppendCore(IEnumerable datasource, Func indexSelector, IComparer comparer) - { - var tableName = typeof(T).GetCustomAttribute(); - if (tableName == null) throw new InvalidOperationException("Type is not annotated MemoryTableAttribute. Type:" + typeof(T).FullName); - - if (header.ContainsKey(tableName.TableName)) - { - throw new InvalidOperationException("TableName is already appended in builder. TableName: " + tableName.TableName + " Type:" + typeof(T).FullName); - } - - if (datasource == null) return; - - // sort(as indexed data-table) - var source = FastSort(datasource, indexSelector, comparer); - - // write data and store header-data. - var useOption = options ?? MessagePackSerializer.DefaultOptions.WithCompression(MessagePackCompression.Lz4Block); - - var offset = bufferWriter.CurrentOffset; - MessagePackSerializer.Serialize(bufferWriter, source, useOption); - - header.Add(tableName.TableName, (offset, bufferWriter.CurrentOffset - offset)); - } - - static TElement[] FastSort(IEnumerable datasource, Func indexSelector, IComparer comparer) - { - var collection = datasource as ICollection; - if (collection != null) - { - var array = new TElement[collection.Count]; - var sortSource = new TKey[collection.Count]; - var i = 0; - foreach (var item in collection) - { - array[i] = item; - sortSource[i] = indexSelector(item); - i++; - } - Array.Sort(sortSource, array, 0, collection.Count, comparer); - return array; - } - else - { - var array = new ExpandableArray(null); - var sortSource = new ExpandableArray(null); - foreach (var item in datasource) - { - array.Add(item); - sortSource.Add(indexSelector(item)); - } - - Array.Sort(sortSource.items, array.items, 0, array.count, comparer); - - Array.Resize(ref array.items, array.count); - return array.items; - } - } - - public byte[] Build() - { - using (var ms = new MemoryStream()) - { - WriteToStream(ms); - return ms.ToArray(); - } - } - - public void WriteToStream(Stream stream) - { - MessagePackSerializer.Serialize(stream, header, HeaderFormatterResolver.StandardOptions); - MemoryMarshal.TryGetArray(bufferWriter.WrittenMemory, out var segment); - stream.Write(segment.Array, segment.Offset, segment.Count); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBase.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBase.cs.meta deleted file mode 100644 index 85e2c14..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1bd7b48a64a527347b521a4c19096f31 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBaseExtensions.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBaseExtensions.cs deleted file mode 100644 index 0be85d7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBaseExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace MasterMemory -{ - public static class DatabaseBuilderExtensions - { - public static void AppendDynamic(this DatabaseBuilderBase builder, Type dataType, IList tableData) - { - var appendMethod = builder.GetType().GetMethods() - .Where(x => x.Name == "Append") - .Where(x => x.GetParameters()[0].ParameterType.GetGenericArguments()[0] == dataType) - .FirstOrDefault(); - - if (appendMethod == null) - { - throw new InvalidOperationException("Append(IEnumerable) can not found. DataType:" + dataType); - } - - var dynamicArray = Array.CreateInstance(dataType, tableData.Count); - for (int i = 0; i < tableData.Count; i++) - { - dynamicArray.SetValue(Convert.ChangeType(tableData[i], dataType), i); - } - - appendMethod.Invoke(builder, new object[] { dynamicArray }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBaseExtensions.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBaseExtensions.cs.meta deleted file mode 100644 index 88dfe83..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/DatabaseBuilderBaseExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f1c743e6e8a8434469708c8b790ddcbf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/IValidatable.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/IValidatable.cs deleted file mode 100644 index 290fe6d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/IValidatable.cs +++ /dev/null @@ -1,23 +0,0 @@ -using MasterMemory.Validation; -using System; -using System.Linq.Expressions; - -namespace MasterMemory -{ - public interface IValidatable - { - void Validate(IValidator validator); - } - - public interface IValidator - { - ValidatableSet GetTableSet(); - ReferenceSet GetReferenceSet(); - void Validate(Expression> predicate); - void Validate(Func predicate, string message); - void ValidateAction(Expression> predicate); - void ValidateAction(Func predicate, string message); - void Fail(string message); - bool CallOnce(); - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/IValidatable.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/IValidatable.cs.meta deleted file mode 100644 index bf99342..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/IValidatable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f6d9227652e32df4c8f24eb6138f74a7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/ImmutableBuilderBase.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/ImmutableBuilderBase.cs deleted file mode 100644 index c7f0474..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/ImmutableBuilderBase.cs +++ /dev/null @@ -1,79 +0,0 @@ -using MasterMemory.Internal; -using System; -using System.Collections.Generic; - -namespace MasterMemory -{ - public abstract class ImmutableBuilderBase - { - static protected TElement[] CloneAndSortBy(IList elementData, Func indexSelector, IComparer comparer) - { - var array = new TElement[elementData.Count]; - var sortSource = new TKey[elementData.Count]; - for (int i = 0; i < elementData.Count; i++) - { - array[i] = elementData[i]; - sortSource[i] = indexSelector(elementData[i]); - } - - Array.Sort(sortSource, array, 0, array.Length, comparer); - return array; - } - - static protected List RemoveCore(TElement[] array, TKey[] keys, Func keySelector, IComparer comparer) - { - var removeIndexes = new HashSet(); - foreach (var key in keys) - { - var index = BinarySearch.FindFirst(array, key, keySelector, comparer); - if (index != -1) - { - removeIndexes.Add(index); - } - } - - var newList = new List(array.Length - removeIndexes.Count); - for (int i = 0; i < array.Length; i++) - { - if (!removeIndexes.Contains(i)) - { - newList.Add(array[i]); - } - } - - return newList; - } - - static protected List DiffCore(TElement[] array, TElement[] addOrReplaceData, Func keySelector, IComparer comparer) - { - var newList = new List(array.Length); - var replaceIndexes = new Dictionary(); - foreach (var data in addOrReplaceData) - { - var index = BinarySearch.FindFirst(array, keySelector(data), keySelector, comparer); - if (index != -1) - { - replaceIndexes.Add(index, data); - } - else - { - newList.Add(data); - } - } - - for (int i = 0; i < array.Length; i++) - { - if (replaceIndexes.TryGetValue(i, out var data)) - { - newList.Add(data); - } - else - { - newList.Add(array[i]); - } - } - - return newList; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/ImmutableBuilderBase.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/ImmutableBuilderBase.cs.meta deleted file mode 100644 index ec4a8e7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/ImmutableBuilderBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 31fabae7e48648a49a27e79f240949ef -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal.meta deleted file mode 100644 index 587e786..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 7aad9829df17a4b4aa55d3a292fb904c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/BinarySearch.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/BinarySearch.cs deleted file mode 100644 index 19af7a5..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/BinarySearch.cs +++ /dev/null @@ -1,220 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace MasterMemory.Internal -{ - internal static class BinarySearch - { - public static int FindFirst(T[] array, TKey key, Func selector, IComparer comparer) - { - var lo = 0; - var hi = array.Length - 1; - - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var found = comparer.Compare(selector(array[mid]), key); - - if (found == 0) return mid; - if (found < 0) - { - lo = mid + 1; - } - else - { - hi = mid - 1; - } - } - - return -1; - } - - public static int FindFirstIntKey(T[] array, int key, Func selector) - { - var lo = 0; - var hi = array.Length - 1; - - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - // compare inlining - var selectedValue = selector(array[mid]); - var found = (selectedValue < key) ? -1 : (selectedValue > key) ? 1 : 0; - - if (found == 0) return mid; - if (found < 0) - { - lo = mid + 1; - } - else - { - hi = mid - 1; - } - } - - return -1; - } - - // lo = 0, hi = Count. - public static int FindClosest(T[] array, int lo, int hi, TKey key, Func selector, IComparer comparer, bool selectLower) - { - if (array.Length == 0) return -1; - - lo = lo - 1; - - while (hi - lo > 1) - { - var mid = lo + ((hi - lo) >> 1); - var found = comparer.Compare(selector(array[mid]), key); - - if (found == 0) - { - lo = hi = mid; - break; - } - if (found >= 1) - { - hi = mid; - } - else - { - lo = mid; - } - } - - return selectLower ? lo : hi; - } - - // default lo = 0, hi = array.Count - public static int LowerBound(T[] array, int lo, int hi, TKey key, Func selector, IComparer comparer) - { - while (lo < hi) - { - var mid = lo + ((hi - lo) >> 1); - var found = comparer.Compare(key, selector(array[mid])); - - if (found <= 0) - { - hi = mid; - } - else - { - lo = mid + 1; - } - } - - var index = lo; - if (index == -1 || array.Length <= index) - { - return -1; - } - - // check final - return (comparer.Compare(key, selector(array[index])) == 0) - ? index - : -1; - } - - public static int UpperBound(T[] array, int lo, int hi, TKey key, Func selector, IComparer comparer) - { - while (lo < hi) - { - var mid = lo + ((hi - lo) >> 1); - var found = comparer.Compare(key, selector(array[mid])); - - if (found >= 0) - { - lo = mid + 1; - } - else - { - hi = mid; - } - } - - var index = (lo == 0) ? 0 : lo - 1; - if (index == -1 || array.Length <= index) - { - return -1; - } - - // check final - return (comparer.Compare(key, selector(array[index])) == 0) - ? index - : -1; - } - - - //... want the lowest index of Key <= Value - //... returns 0 if key is <= all values in array - //... returns array.Length if key is > all values in array - - public static int LowerBoundClosest(T[] array, int lo, int hi, TKey key, Func selector, IComparer comparer) - { - while (lo < hi) - { - var mid = lo + ((hi - lo) >> 1); - var found = comparer.Compare(key, selector(array[mid])); - - if (found <= 0) //... Key is <= value at mid - { - hi = mid; - } - else - { - lo = mid + 1; //... Notice that lo starts at zero and can only increase - } - } - - var index = lo; //... index will always be zero or greater - - if ( array.Length <= index) - { - return array.Length; - } - - // check final - return (comparer.Compare(key, selector(array[index])) <= 0) - ? index - : -1; - } - - - //... want the highest index of Key >= Value - //... returns -1 if key is < than all values in array - //... returns array.Length - 1 if key is >= than all values in array - - public static int UpperBoundClosest(T[] array, int lo, int hi, TKey key, Func selector, IComparer comparer) - { - while (lo < hi) - { - var mid = lo + ((hi - lo) >> 1); - var found = comparer.Compare(key, selector(array[mid])); - - if (found >= 0) //... Key >= value at mid - { - lo = mid + 1; //... Note lo starts at zero and can only increase - } - else - { - hi = mid; - } - } - - var index = (lo == 0) ? 0 : lo - 1; //... index will always be zero or greater - - if ( index >= array.Length ) - { - return array.Length; - } - - // check final - return (comparer.Compare(key, selector(array[index])) >= 0) - ? index - : -1; - } - - - - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/BinarySearch.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/BinarySearch.cs.meta deleted file mode 100644 index bf85ce3..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/BinarySearch.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 484ebcce15c968c4999154bf258d92c5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ByteBufferWriter.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ByteBufferWriter.cs deleted file mode 100644 index 73a215d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ByteBufferWriter.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Buffers; - -namespace MasterMemory -{ - internal class ByteBufferWriter : IBufferWriter - { - byte[] buffer; - int index; - - public int CurrentOffset => index; - public ReadOnlySpan WrittenSpan => buffer.AsSpan(0, index); - public ReadOnlyMemory WrittenMemory => new ReadOnlyMemory(buffer, 0, index); - - public ByteBufferWriter() - { - buffer = new byte[1024]; - index = 0; - } - - public void Advance(int count) - { - index += count; - } - - public Memory GetMemory(int sizeHint = 0) - { - AGAIN: - var nextSize = index + sizeHint; - if (buffer.Length < nextSize) - { - Array.Resize(ref buffer, Math.Max(buffer.Length * 2, nextSize)); - } - - if (sizeHint == 0) - { - var result = new Memory(buffer, index, buffer.Length - index); - if (result.Length == 0) - { - sizeHint = 1024; - goto AGAIN; - } - return result; - } - else - { - return new Memory(buffer, index, sizeHint); - } - } - - public Span GetSpan(int sizeHint = 0) - { - return GetMemory(sizeHint).Span; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ByteBufferWriter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ByteBufferWriter.cs.meta deleted file mode 100644 index 35f8df8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ByteBufferWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 55da238706ec3db49b77f741231cce93 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ExpandableArray.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ExpandableArray.cs deleted file mode 100644 index e68f197..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ExpandableArray.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; - -namespace MasterMemory.Internal -{ - internal struct ExpandableArray - { - internal TElement[] items; - internal int count; - - public ExpandableArray(object dummy) - { - items = Array.Empty(); - count = 0; - } - - internal void Add(TElement item) - { - if (items == null || items.Length == 0) - { - items = new TElement[4]; - } - else if (items.Length == (count + 1)) - { - Array.Resize(ref items, checked(count * 2)); - } - items[count++] = item; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ExpandableArray.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ExpandableArray.cs.meta deleted file mode 100644 index 196e14a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/ExpandableArray.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8957871877e5e1c4a9e75e7333684db8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/HeaderFormatterResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/HeaderFormatterResolver.cs deleted file mode 100644 index 4b4f3b7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/HeaderFormatterResolver.cs +++ /dev/null @@ -1,62 +0,0 @@ -using MessagePack; -using MessagePack.Formatters; -using System; -using System.Collections.Generic; - -namespace MasterMemory.Internal -{ - // for AOT(IL2CPP) concrete generic formatter. - internal class HeaderFormatterResolver : IFormatterResolver - { - public static readonly IFormatterResolver Instance = new HeaderFormatterResolver(); - public static readonly MessagePackSerializerOptions StandardOptions = MessagePackSerializerOptions.Standard.WithResolver(Instance); - - public IMessagePackFormatter GetFormatter() - { - if (typeof(T) == typeof(Dictionary)) - { - return (IMessagePackFormatter)(object)new DictionaryFormatter(); - } - else if (typeof(T) == typeof(string)) - { - return (IMessagePackFormatter)(object)NullableStringFormatter.Instance; - } - else if (typeof(T) == typeof((int, int))) - { - return (IMessagePackFormatter)(object)new IntIntValueTupleFormatter(); - } - else if (typeof(T) == typeof(int)) - { - return (IMessagePackFormatter)(object)Int32Formatter.Instance; - } - - return null; - } - } - - internal sealed class IntIntValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, (int, int) value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.WriteInt32(value.Item1); - writer.WriteInt32(value.Item2); - } - - public (int, int) Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("Data is Nil, ValueTuple can not be null."); - } - - var count = reader.ReadArrayHeader(); - if (count != 2) throw new InvalidOperationException("Invalid ValueTuple count"); - - var item1 = reader.ReadInt32(); - var item2 = reader.ReadInt32(); - - return new ValueTuple(item1, item2); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/HeaderFormatterResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/HeaderFormatterResolver.cs.meta deleted file mode 100644 index 43de56c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/HeaderFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0fceb9129ece23c4abf9e32cfbbbafe8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/InternStringResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/InternStringResolver.cs deleted file mode 100644 index d3adef8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/InternStringResolver.cs +++ /dev/null @@ -1,42 +0,0 @@ -using MessagePack; -using MessagePack.Formatters; -using System; - -namespace MasterMemory.Internal -{ - internal class InternStringResolver : IFormatterResolver, IMessagePackFormatter - { - readonly IFormatterResolver innerResolver; - - public InternStringResolver(IFormatterResolver innerResolver) - { - this.innerResolver = innerResolver; - } - - public IMessagePackFormatter GetFormatter() - { - if (typeof(T) == typeof(string)) - { - return (IMessagePackFormatter)this; - } - - return innerResolver.GetFormatter(); - } - - string IMessagePackFormatter.Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var str = reader.ReadString(); - if (str == null) - { - return null; - } - - return string.Intern(str); - } - - void IMessagePackFormatter.Serialize(ref MessagePackWriter writer, string value, MessagePackSerializerOptions options) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/InternStringResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/InternStringResolver.cs.meta deleted file mode 100644 index 9d91f84..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Internal/InternStringResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 14c7daaee38ed54429b50b1285ef932c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MasterMemory.asmdef b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MasterMemory.asmdef deleted file mode 100644 index 0558748..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MasterMemory.asmdef +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "MasterMemory", - "references": [ - "MessagePack", - "MessagePack.Annotations" - ], - "optionalUnityReferences": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [ - "System.Memory.dll", - "System.Buffers.dll", - "System.Runtime.CompilerServices.Unsafe.dll" - ], - "autoReferenced": true, - "defineConstraints": [] -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MasterMemory.asmdef.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MasterMemory.asmdef.meta deleted file mode 100644 index e3797be..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MasterMemory.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 0632cc6b22db61d41898dfef78dc32f5 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MemoryDatabaseBase.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MemoryDatabaseBase.cs deleted file mode 100644 index d1d873d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MemoryDatabaseBase.cs +++ /dev/null @@ -1,117 +0,0 @@ -using MasterMemory.Internal; -using MessagePack; -using MessagePack.Formatters; -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Linq; -using System.Buffers; -using MasterMemory.Validation; - -namespace MasterMemory -{ - public abstract class MemoryDatabaseBase - { - protected MemoryDatabaseBase() - { - - } - - public MemoryDatabaseBase(byte[] databaseBinary, bool internString = true, IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) - { - var reader = new MessagePackReader(databaseBinary); - var formatter = new DictionaryFormatter(); - - var header = formatter.Deserialize(ref reader, HeaderFormatterResolver.StandardOptions); - var resolver = formatterResolver ?? MessagePackSerializer.DefaultOptions.Resolver; - if (internString) - { - resolver = new InternStringResolver(resolver); - } - if (maxDegreeOfParallelism < 1) - { - maxDegreeOfParallelism = 1; - } - - Init(header, databaseBinary.AsMemory((int)reader.Consumed), MessagePackSerializer.DefaultOptions.WithResolver(resolver).WithCompression(MessagePackCompression.Lz4Block), maxDegreeOfParallelism); - } - - protected static TView ExtractTableData(Dictionary header, ReadOnlyMemory databaseBinary, MessagePackSerializerOptions options, Func createView) - { - var tableName = typeof(T).GetCustomAttribute(); - if (tableName == null) throw new InvalidOperationException("Type is not annotated MemoryTableAttribute. Type:" + typeof(T).FullName); - - if (header.TryGetValue(tableName.TableName, out var segment)) - { - var data = MessagePackSerializer.Deserialize(databaseBinary.Slice(segment.offset, segment.count), options); - return createView(data); - } - else - { - // return empty - var data = Array.Empty(); - return createView(data); - } - } - - protected abstract void Init(Dictionary header, ReadOnlyMemory databaseBinary, MessagePackSerializerOptions options, int maxDegreeOfParallelism); - - public static TableInfo[] GetTableInfo(byte[] databaseBinary, bool storeTableData = true) - { - var formatter = new DictionaryFormatter(); - var reader = new MessagePackReader(databaseBinary); - var header = formatter.Deserialize(ref reader, HeaderFormatterResolver.StandardOptions); - - return header.Select(x => new TableInfo(x.Key, x.Value.Item2, storeTableData ? databaseBinary : null, x.Value.Item1)).ToArray(); - } - - protected void ValidateTable(IReadOnlyList table, ValidationDatabase database, string pkName, Delegate pkSelector, ValidateResult result) - { - var onceCalled = new System.Runtime.CompilerServices.StrongBox(false); - foreach (var item in table) - { - if (item is IValidatable validatable) - { - var validator = new Validator(database, item, result, onceCalled, pkName, pkSelector); - validatable.Validate(validator); - } - } - } - } - - /// - /// Diagnostic info of MasterMemory's table. - /// - public class TableInfo - { - public string TableName { get; } - public int Size { get; } - byte[] binaryData; - - public TableInfo(string tableName, int size, byte[] rawBinary, int offset) - { - TableName = tableName; - Size = size; - if (rawBinary != null) - { - this.binaryData = new byte[size]; - Array.Copy(rawBinary, offset, binaryData, 0, size); - } - } - - public string DumpAsJson() - { - return DumpAsJson(MessagePackSerializer.DefaultOptions); - } - - public string DumpAsJson(MessagePackSerializerOptions options) - { - if (binaryData == null) - { - throw new InvalidOperationException("DumpAsJson can only call from GetTableInfo(storeTableData = true)."); - } - - return MessagePackSerializer.ConvertToJson(binaryData, options.WithCompression(MessagePackCompression.Lz4Block)); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MemoryDatabaseBase.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MemoryDatabaseBase.cs.meta deleted file mode 100644 index 51bdcbf..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/MemoryDatabaseBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: caf403ac6fae40743a3a96df0443d003 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta.meta deleted file mode 100644 index d5c27d3..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 97ae46309ad9803459c4fb1e11a5f524 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta/Meta.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta/Meta.cs deleted file mode 100644 index da1e23f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta/Meta.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Reflection; -using System.Text; - -namespace MasterMemory.Meta -{ - public class MetaDatabase - { - IDictionary tableInfos; - - public MetaDatabase(IDictionary tableInfos) - { - this.tableInfos = tableInfos; - } - - public int Count => tableInfos.Count; - - public IEnumerable GetTableInfos() - { - foreach (var item in tableInfos.Values) - { - yield return item; - } - } - - public MetaTable GetTableInfo(string tableName) - { - return tableInfos.TryGetValue(tableName, out var table) - ? table - : null; - } - } - - public class MetaTable - { - public Type DataType { get; } - public Type TableType { get; } - public string TableName { get; } - public IReadOnlyList Properties { get; } - public IReadOnlyList Indexes { get; } - - public MetaTable(Type dataType, Type tableType, string tableName, IReadOnlyList properties, IReadOnlyList Indexes) - { - this.DataType = dataType; - this.TableType = tableType; - this.TableName = tableName; - this.Properties = properties; - this.Indexes = Indexes; - } - - public override string ToString() - { - return TableName; - } - } - - public class MetaProperty - { - public PropertyInfo PropertyInfo { get; } - - public string Name => PropertyInfo.Name; - public string NameLowerCamel => ToCamelCase(PropertyInfo.Name); - public string NameSnakeCase => ToSnakeCase(PropertyInfo.Name); - - public MetaProperty(PropertyInfo propertyInfo) - { - PropertyInfo = propertyInfo; - } - - public override string ToString() - { - return Name; - } - - /// - /// MyProperty -> myProperty - /// - static string ToCamelCase(string s) - { - if (string.IsNullOrEmpty(s) || char.IsLower(s, 0)) - { - return s; - } - - var array = s.ToCharArray(); - array[0] = char.ToLowerInvariant(array[0]); - return new string(array); - } - - /// - /// MyProperty -> my_property - /// - static string ToSnakeCase(string s) - { - if (string.IsNullOrEmpty(s)) return s; - - var sb = new StringBuilder(); - for (int i = 0; i < s.Length; i++) - { - var c = s[i]; - - if (Char.IsUpper(c)) - { - // first - if (i == 0) - { - sb.Append(char.ToLowerInvariant(c)); - } - else if (char.IsUpper(s[i - 1])) // WriteIO => write_io - { - sb.Append(char.ToLowerInvariant(c)); - } - else - { - sb.Append("_"); - sb.Append(char.ToLowerInvariant(c)); - } - } - else - { - sb.Append(c); - } - } - - return sb.ToString(); - } - } - - public class MetaIndex - { - public IReadOnlyList IndexProperties { get; } - public bool IsPrimaryIndex { get; } - public bool IsUnique { get; } - public System.Collections.IComparer Comparer { get; } - public bool IsReturnRangeValue => IndexProperties.Count != 1; - - public MetaIndex(IReadOnlyList indexProperties, bool isPrimaryIndex, bool isUnique, System.Collections.IComparer comparer) - { - IndexProperties = indexProperties; - IsPrimaryIndex = isPrimaryIndex; - IsUnique = isUnique; - Comparer = comparer; - } - - public override string ToString() - { - return string.Join(", ", IndexProperties.Select(x => x.Name)); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta/Meta.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta/Meta.cs.meta deleted file mode 100644 index 0f9e51f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Meta/Meta.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c32f40126bffe2b4982a0c9371f4470f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/RangeView.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/RangeView.cs deleted file mode 100644 index 1a9be6f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/RangeView.cs +++ /dev/null @@ -1,150 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; - -namespace MasterMemory -{ - public readonly struct RangeView : IEnumerable, IReadOnlyList, IList - { - public static RangeView Empty => new RangeView( null, -1, -1, false ); - - readonly T[] orderedData; - readonly int left; - readonly int right; - readonly bool ascendant; - readonly bool hasValue; - - public int Count => (!hasValue) ? 0 : (right - left) + 1; - public T First => this[0]; - public T Last => this[Count - 1]; - - public RangeView Reverse => new RangeView(orderedData, left, right, !ascendant); - - internal int FirstIndex => ascendant ? left : right; - internal int LastIndex => ascendant ? right : left; - - bool ICollection.IsReadOnly => true; - - public T this[int index] - { - get - { - if (!hasValue) throw new ArgumentOutOfRangeException("view is empty"); - if (index < 0) throw new ArgumentOutOfRangeException("index < 0"); - if (Count <= index) throw new ArgumentOutOfRangeException("count <= index"); - - if (ascendant) - { - return orderedData[left + index]; - } - else - { - return orderedData[right - index]; - } - } - } - - public RangeView(T[] orderedData, int left, int right, bool ascendant) - { - this.hasValue = (orderedData != null ) && (orderedData.Length != 0) && (left <= right); // same index is length = 1 this.orderedData = orderedData; - this.orderedData = orderedData; - this.left = left; - this.right = right; - this.ascendant = ascendant; - } - - public IEnumerator GetEnumerator() - { - var count = Count; - for (int i = 0; i < count; i++) - { - yield return this[i]; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public bool Any() - { - return Count != 0; - } - - public int IndexOf(T item) - { - var i = 0; - foreach (var v in this) - { - if (EqualityComparer.Default.Equals(v, item)) - { - return i; - } - i++; - } - return -1; - } - - public bool Contains(T item) - { - var count = Count; - for (int i = 0; i < count; i++) - { - var v = this[i]; - if (EqualityComparer.Default.Equals(v, item)) - { - return true; - } - } - return false; - } - - public void CopyTo(T[] array, int arrayIndex) - { - var count = Count; - Array.Copy(orderedData, left, array, arrayIndex, count); - if (!ascendant) - { - Array.Reverse(array, arrayIndex, count); - } - } - - T IList.this[int index] - { - get - { - return this[index]; - } - set - { - throw new NotImplementedException(); - } - } - - void IList.Insert(int index, T item) - { - throw new NotSupportedException(); - } - - void IList.RemoveAt(int index) - { - throw new NotSupportedException(); - } - - void ICollection.Add(T item) - { - throw new NotSupportedException(); - } - - void ICollection.Clear() - { - throw new NotSupportedException(); - } - - bool ICollection.Remove(T item) - { - throw new NotSupportedException(); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/RangeView.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/RangeView.cs.meta deleted file mode 100644 index beadb8e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/RangeView.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6834e28efa5e0fb4ca1668127b29ce29 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/TableBase.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/TableBase.cs deleted file mode 100644 index 85e114d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/TableBase.cs +++ /dev/null @@ -1,194 +0,0 @@ -using MasterMemory.Internal; -using MasterMemory.Validation; -using System; -using System.Collections.Generic; -using System.Diagnostics; - -namespace MasterMemory -{ - public abstract class TableBase - { - protected readonly TElement[] data; - - // Common Properties - public int Count => data.Length; - public RangeView All => new RangeView(data, 0, data.Length - 1, true); - public RangeView AllReverse => new RangeView(data, 0, data.Length - 1, false); - public TElement[] GetRawDataUnsafe() => data; - - public TableBase(TElement[] sortedData) - { - this.data = sortedData; - } - - // Validate - - static protected void ValidateUniqueCore(TElement[] indexArray, Func keySelector, string message, ValidateResult resultSet) - { - var set = new HashSet(); - foreach (var item in indexArray) - { - var v = keySelector(item); - if (!set.Add(v)) - { - resultSet.AddFail(typeof(TElement), "Unique failed: " + message + ", value = " + v, item); - } - } - } - - // Util - - protected TElement[] CloneAndSortBy(Func indexSelector, IComparer comparer) - { - var array = new TElement[data.Length]; - var sortSource = new TKey[data.Length]; - for (int i = 0; i < data.Length; i++) - { - array[i] = data[i]; - sortSource[i] = indexSelector(data[i]); - } - - Array.Sort(sortSource, array, 0, array.Length, comparer); - return array; - } - - static protected TElement ThrowKeyNotFound(TKey key) - { - throw new KeyNotFoundException("DataType: " + typeof(TElement).FullName + ", Key: " + key.ToString()); - } - - // Unique - - static protected TElement FindUniqueCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey key, bool throwIfNotFound = true) - { - var index = BinarySearch.FindFirst(indexArray, key, keySelector, comparer); - if (index != -1) - { - return indexArray[index]; - } - else - { - if (throwIfNotFound) - { - ThrowKeyNotFound(key); - } - return default; - } - } - - // Optimize for IntKey - static protected TElement FindUniqueCoreInt(TElement[] indexArray, Func keySelector, IComparer _, int key, bool throwIfNotFound = true) - { - var index = BinarySearch.FindFirstIntKey(indexArray, key, keySelector); - if (index != -1) - { - return indexArray[index]; - } - else - { - if (throwIfNotFound) - { - ThrowKeyNotFound(key); - } - return default; - } - } - - static protected bool TryFindUniqueCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey key, out TElement result) - { - var index = BinarySearch.FindFirst(indexArray, key, keySelector, comparer); - if (index != -1) - { - result = indexArray[index]; - return true; - } - else - { - result = default; - return false; - } - } - - static protected bool TryFindUniqueCoreInt(TElement[] indexArray, Func keySelector, IComparer _, int key, out TElement result) - { - var index = BinarySearch.FindFirstIntKey(indexArray, key, keySelector); - if (index != -1) - { - result = indexArray[index]; - return true; - } - else - { - result = default; - return false; - } - } - - static protected TElement FindUniqueClosestCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey key, bool selectLower) - { - var index = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, key, keySelector, comparer, selectLower); - return (index != -1) ? indexArray[index] : default(TElement); - } - - static protected RangeView FindUniqueRangeCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey min, TKey max, bool ascendant) - { - var lo = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, min, keySelector, comparer, false); - var hi = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, max, keySelector, comparer, true); - - if ( lo == -1 ) lo = 0; - if ( hi == indexArray.Length ) hi -= 1; - - return new RangeView(indexArray, lo, hi, ascendant); - } - - // Many - - static protected RangeView FindManyCore(TElement[] indexKeys, Func keySelector, IComparer comparer, TKey key) - { - var lo = BinarySearch.LowerBound(indexKeys, 0, indexKeys.Length, key, keySelector, comparer); - if (lo == -1) return RangeView.Empty; - - var hi = BinarySearch.UpperBound(indexKeys, 0, indexKeys.Length, key, keySelector, comparer); - if (hi == -1) return RangeView.Empty; - - return new RangeView(indexKeys, lo, hi, true); - } - - static protected RangeView FindManyClosestCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey key, bool selectLower) - { - var closest = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, key, keySelector, comparer, selectLower); - - if ((closest == -1) || ( closest >= indexArray.Length )) - return RangeView.Empty; - - return FindManyCore(indexArray, keySelector, comparer, keySelector(indexArray[closest])); - } - - static protected RangeView FindManyRangeCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey min, TKey max, bool ascendant) - { - //... Empty set when min > max - //... Alternatively, could treat this as between and swap min and max. - - if ( Comparer.Default.Compare( min, max ) > 0 ) - return RangeView.Empty; - - //... want lo to be the lowest index of the values >= than min. - //... lo should be in the range [0,arraylength] - - var lo = BinarySearch.LowerBoundClosest(indexArray, 0, indexArray.Length, min, keySelector, comparer ); - - //... want hi to be the highest index of the values <= than max - //... hi should be in the range [-1,arraylength-1] - - var hi = BinarySearch.UpperBoundClosest(indexArray, 0, indexArray.Length, max, keySelector, comparer ); - - Debug.Assert( lo >= 0 ); - Debug.Assert( hi < indexArray.Length ); - - if ( hi < lo ) - return RangeView.Empty; - - return new RangeView(indexArray, lo, hi, ascendant); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/TableBase.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/TableBase.cs.meta deleted file mode 100644 index 4dc0e94..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/TableBase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 41bd2996d28d5114f8e1d1186ac73b7f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation.meta deleted file mode 100644 index ad7b497..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: ccd9fc821d2ea094fbd5f68730ed5585 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionDumper.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionDumper.cs deleted file mode 100644 index a5eebc7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionDumper.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; -using System.Text; - -namespace MasterMemory.Validation -{ - internal class ExpressionDumper : ExpressionVisitor - { - ParameterExpression param; - T target; - - public Dictionary Members { get; private set; } - - public ExpressionDumper(T target, ParameterExpression param) - { - this.target = target; - this.param = param; - this.Members = new Dictionary(); - } - - protected override System.Linq.Expressions.Expression VisitMember(MemberExpression node) - { - if (node.Expression == param && !Members.ContainsKey(node.Member.Name)) - { - var accessor = new ReflectAccessor(target, node.Member.Name); - Members.Add(node.Member.Name, accessor.GetValue()); - } - - return base.VisitMember(node); - } - - public static string DumpMemberValues(T item, Expression> predicate) - { - var dumper = new ExpressionDumper(item, predicate.Parameters.Single()); - return dumper.VisitAndFormat(predicate); - } - - public string VisitAndFormat(Expression expression) - { - Visit(expression); - return string.Join(", ", Members.Select(kvp => kvp.Key + " = " + kvp.Value)); - } - - private class ReflectAccessor - { - public Func GetValue { get; private set; } - public Action SetValue { get; private set; } - - public ReflectAccessor(T target, string name) - { - var field = typeof(T).GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (field != null) - { - GetValue = () => field.GetValue(target); - SetValue = value => field.SetValue(target, value); - return; - } - - var prop = typeof(T).GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (prop != null) - { - GetValue = () => prop.GetValue(target, null); - SetValue = value => prop.SetValue(target, value, null); - return; - } - - throw new ArgumentException(string.Format("\"{0}\" not found : Type <{1}>", name, typeof(T).Name)); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionDumper.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionDumper.cs.meta deleted file mode 100644 index 75f34be..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionDumper.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eaa46743799322d4abdd09c4f4e0f847 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionParameterNameModifier.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionParameterNameModifier.cs deleted file mode 100644 index c996c74..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionParameterNameModifier.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Linq.Expressions; - -namespace MasterMemory.Validation -{ - public class ExpressionParameterNameModifier : ExpressionVisitor - { - readonly ParameterExpression modifyTarget; - readonly ParameterExpression replaceExpression; - - public ExpressionParameterNameModifier(ParameterExpression modifyTarget, ParameterExpression replaceExpression) - { - this.modifyTarget = modifyTarget; - this.replaceExpression = replaceExpression; - } - - protected override Expression VisitParameter(ParameterExpression node) - { - if (node == modifyTarget) - { - return replaceExpression; - } - - return base.VisitParameter(node); - } - } - - public static class ExpressionParameterNameModifyExtensions - { - public static string ToThisBodyString(this Expression> predicate) - { - var newNameParameter = Expression.Parameter(typeof(T), "this"); - var newExpression = new ExpressionParameterNameModifier(predicate.Parameters[0], newNameParameter).Visit(predicate); - return (newExpression as Expression>).Body.ToString(); - } - - public static string ToSpaceBodyString(this Expression> selector) - { - var newNameParameter = Expression.Parameter(typeof(T), " "); - var newExpression = new ExpressionParameterNameModifier(selector.Parameters[0], newNameParameter).Visit(selector); - return (newExpression as Expression>).Body.ToString(); - } - - public static string ToNameBodyString(this Expression> selector, string newName) - { - var newNameParameter = Expression.Parameter(typeof(T), newName); - var newExpression = new ExpressionParameterNameModifier(selector.Parameters[0], newNameParameter).Visit(selector); - return (newExpression as Expression>).Body.ToString(); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionParameterNameModifier.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionParameterNameModifier.cs.meta deleted file mode 100644 index 8f90c36..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ExpressionParameterNameModifier.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b01dfaeacf4e20545999aeae3148f255 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ITableUniqueValidate.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ITableUniqueValidate.cs deleted file mode 100644 index 2d62070..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ITableUniqueValidate.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace MasterMemory.Validation -{ - public interface ITableUniqueValidate - { - void ValidateUnique(ValidateResult resultSet); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ITableUniqueValidate.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ITableUniqueValidate.cs.meta deleted file mode 100644 index 814bc3b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ITableUniqueValidate.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1ff3686ca82b74f4e8c2666931ab939a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ReferenceSet.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ReferenceSet.cs deleted file mode 100644 index 12d3ceb..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ReferenceSet.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Linq.Expressions; - -namespace MasterMemory.Validation -{ - public class ReferenceSet - { - readonly TElement item; - readonly IReadOnlyList referenceTable; - readonly ValidateResult resultSet; - readonly string pkName; - readonly Delegate pkSelector; - - public IReadOnlyList TableData => referenceTable; - - public ReferenceSet(TElement item, IReadOnlyList referenceTable, ValidateResult resultSet, string pkName, Delegate pkSelector) - { - this.item = item; - this.referenceTable = referenceTable; - this.resultSet = resultSet; - this.pkName = pkName; - this.pkSelector = pkSelector; - } - - public void Exists(Expression> elementSelector, Expression> referenceElementSelector) - { - Exists(elementSelector, referenceElementSelector, EqualityComparer.Default); - } - - public void Exists(Expression> elementSelector, Expression> referenceElementSelector, EqualityComparer equalityComparer) - { - var f1 = elementSelector.Compile(true); - var f2 = referenceElementSelector.Compile(true); - - var compareBase = f1(item); - foreach (var refItem in referenceTable) - { - if (equalityComparer.Equals(compareBase, f2(refItem))) - { - return; - } - } - - // not found, assert. - var from = elementSelector.ToNameBodyString(typeof(TElement).Name); - var to = referenceElementSelector.ToNameBodyString(typeof(TReference).Name); - resultSet.AddFail(typeof(TElement), "Exists failed: " + from + " -> " + to + ", value = " + compareBase + ", " + BuildPkMessage(), item); - } - - string BuildPkMessage() - { - var pk = pkSelector.DynamicInvoke(item).ToString(); - return $"PK({pkName}) = {pk}"; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ReferenceSet.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ReferenceSet.cs.meta deleted file mode 100644 index e5f8a22..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ReferenceSet.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3d80126e728827d4e8042cb26309de4f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.Sequential.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.Sequential.cs deleted file mode 100644 index 2b8f498..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.Sequential.cs +++ /dev/null @@ -1,283 +0,0 @@ - -using System; -using System.Linq; -using System.Linq.Expressions; - -namespace MasterMemory.Validation -{ - public partial class ValidatableSet - { - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - public void Sequential(Expression> selector, bool distinct = false) - { - var f = selector.Compile(true); - SequentialCore(f, () => selector.ToSpaceBodyString(), distinct); - } - - public void Sequential(Func selector, string message, bool distinct = false) - { - SequentialCore(selector, () => " " + message, distinct); - } - - void SequentialCore(Func selector, Func message, bool distinct) - { - if (tableData.Count == 0) return; - var data = tableData.OrderBy(selector).ToArray(); - - var prev = selector(data[0]); - for (int i = 1; i < data.Length; i++) - { - var curr = selector(data[i]); - if (distinct) - { - if (prev == curr) continue; - } - - if ((prev + 1) != curr) - { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); - } - - prev = curr; - } - } - - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.Sequential.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.Sequential.cs.meta deleted file mode 100644 index d470082..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.Sequential.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0b5c72be2e808484cb055c14a932f738 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.cs deleted file mode 100644 index 5ebe6e3..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; - -namespace MasterMemory.Validation -{ - public partial class ValidatableSet - { - readonly IReadOnlyList tableData; - readonly ValidateResult resultSet; - readonly string pkName; - readonly Delegate pkSelector; - - public ValidatableSet(IReadOnlyList tableData, ValidateResult resultSet, string pkName, Delegate pkSelector) - { - this.tableData = tableData; - this.resultSet = resultSet; - this.pkName = pkName; - this.pkSelector = pkSelector; - } - - public IReadOnlyList TableData => tableData; - - public void Unique(Expression> selector) - { - Unique(selector, EqualityComparer.Default); - } - - public void Unique(Expression> selector, IEqualityComparer equalityComparer) - { - var f = selector.Compile(true); - - var set = new HashSet(equalityComparer); - foreach (var item in tableData) - { - var v = f(item); - if (!set.Add(v)) - { - resultSet.AddFail(typeof(TElement), "Unique failed:" + selector.ToSpaceBodyString() + ", value = " + v + ", " + BuildPkMessage(item), item); - } - } - } - - public void Unique(Func selector, string message) - { - Unique(selector, EqualityComparer.Default, message); - } - - public void Unique(Func selector, IEqualityComparer equalityComparer, string message) - { - var set = new HashSet(equalityComparer); - foreach (var item in tableData) - { - var v = selector(item); - if (!set.Add(v)) - { - resultSet.AddFail(typeof(TElement), "Unique failed: " + message + ", value = " + v + ", " + BuildPkMessage(item), item); - } - } - } - - public ValidatableSet Where(Func predicate) - { - return new ValidatableSet(tableData.Where(predicate).ToArray(), resultSet, pkName, pkSelector); - } - - string BuildPkMessage(TElement item) - { - var pk = pkSelector.DynamicInvoke(item).ToString(); - return $"PK({pkName}) = {pk}"; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.cs.meta deleted file mode 100644 index 341a1f9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidatableSet.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fb49e34e02e19a644bc90a5c7f3d1227 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidateResult.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidateResult.cs deleted file mode 100644 index c26ad7a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidateResult.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace MasterMemory.Validation -{ - public class ValidateResult - { - List result = new List(); - - public bool IsValidationFailed => result.Count != 0; - - public IReadOnlyList FailedResults => result; - - public string FormatFailedResults() - { - var sb = new StringBuilder(); - foreach (var item in result) - { - sb.AppendLine(item.Type.FullName + " - " + item.Message); - } - return sb.ToString(); - } - - internal void AddFail(Type type, string message, object data) - { - result.Add(new FaildItem(type, message, data)); - } - } - - public readonly struct FaildItem - { - public FaildItem(Type type, string message, object data) - { - Type = type; - Message = message; - Data = data; - } - - public Type Type { get; } - public string Message { get; } - public object Data { get; } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidateResult.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidateResult.cs.meta deleted file mode 100644 index 38149d8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidateResult.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ffad06a1af3242d40b6bc3a63a390bdb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidationDatabase.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidationDatabase.cs deleted file mode 100644 index e6005c0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidationDatabase.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace MasterMemory.Validation -{ - public class ValidationDatabase - { - // {Type, IReadOnlyList } - readonly Dictionary dataTables = new Dictionary(); - - public ValidationDatabase(IEnumerable tables) - { - foreach (var table in tables) - { - // TableBase - var baseType = table.GetType().BaseType; - - // RangeView - var rangeViewAll = baseType.GetProperty("All").GetGetMethod().Invoke(table, null); - - var elementType = baseType.GetGenericArguments()[0]; - dataTables.Add(elementType, rangeViewAll); - } - } - - internal IReadOnlyList GetTable() - { - if (!dataTables.TryGetValue(typeof(T), out var table)) - { - throw new InvalidOperationException("Can not create validator in " + typeof(T).FullName); - } - var data = table as IReadOnlyList; - return data; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidationDatabase.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidationDatabase.cs.meta deleted file mode 100644 index 1ce6bb3..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/ValidationDatabase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 66ed0d6c1115eda4fa50624a875d688f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/Validator.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/Validator.cs deleted file mode 100644 index 4480741..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/Validator.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace MasterMemory.Validation -{ - internal class Validator : IValidator - { - readonly ValidationDatabase database; - readonly T item; - readonly ValidateResult resultSet; - readonly StrongBox onceCalled; - readonly string pkName; - readonly Delegate pkSelector; - - public Validator(ValidationDatabase database, T item, ValidateResult resultSet, StrongBox onceCalled, string pkName, Delegate pkSelector) - { - this.database = database; - this.item = item; - this.resultSet = resultSet; - this.onceCalled = onceCalled; - this.pkName = pkName; - this.pkSelector = pkSelector; - } - - public bool CallOnce() - { - if (!onceCalled.Value) - { - onceCalled.Value = true; - return true; - } - - return false; - } - - public ValidatableSet GetTableSet() - { - return new ValidatableSet(database.GetTable(), resultSet, pkName, pkSelector); - } - - public ReferenceSet GetReferenceSet() - { - var table = database.GetTable(); - return new ReferenceSet(item, table, resultSet, pkName, pkSelector); - } - - public void Validate(Expression> predicate) - { - if (!predicate.Compile(true).Invoke(item)) - { - var memberValues = ExpressionDumper.DumpMemberValues(item, predicate); - var message = string.Format($"{predicate.ToThisBodyString()}, {memberValues}, {BuildPkMessage()}"); - resultSet.AddFail(typeof(T), "Validate failed: " + message, item); - } - } - - public void Validate(Func predicate, string message) - { - if (!predicate(item)) - { - resultSet.AddFail(typeof(T), "Validate failed: " + message + ", " + BuildPkMessage(), item); - } - } - - public void ValidateAction(Expression> predicate) - { - if (!predicate.Compile(true).Invoke()) - { - var expr = predicate.Body.ToString(); - resultSet.AddFail(typeof(T), "ValidateAction failed: " + expr + ", " + BuildPkMessage(), item); - } - } - - public void ValidateAction(Func predicate, string message) - { - if (!predicate()) - { - resultSet.AddFail(typeof(T), "ValidateAction failed: " + message + ", " + BuildPkMessage(), item); - } - } - - public void Fail(string message) - { - resultSet.AddFail(typeof(T), message + ", " + BuildPkMessage(), item); - } - - string BuildPkMessage() - { - var pk = pkSelector.DynamicInvoke(item).ToString(); - return $"PK({pkName}) = {pk}"; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/Validator.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/Validator.cs.meta deleted file mode 100644 index 4bacec2..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Validation/Validator.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9347f35446905294e94d535cffbc0b64 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/_InternalVisibleTo.cs b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/_InternalVisibleTo.cs deleted file mode 100644 index 476a6b5..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/_InternalVisibleTo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("MasterMemory.Tests")] \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/_InternalVisibleTo.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/_InternalVisibleTo.cs.meta deleted file mode 100644 index 7f250ef..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/_InternalVisibleTo.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cf3d88a51d3654140b8601f441bc4e61 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json b/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json deleted file mode 100644 index 62fa51e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "com.cysharp.mastermemory", - "displayName": "MasterMemory", - "version": "2.4.4", - "unity": "2019.3", - "description": "Embedded Typed Readonly In-Memory Document Database for .NET Core and Unity.", - "keywords": [ - "database", - "inmemory-database" - ], - "license": "MIT", - "category": "database", - "dependencies": {} -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack.meta deleted file mode 100644 index 8c26d9a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: d13b481ec71cdd840b26ccce0b511c3c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations.meta deleted file mode 100644 index 1a10052..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: d44b65eb648b9c643ba28d3999c10197 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/Attributes.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/Attributes.cs deleted file mode 100644 index 0ef2733..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/Attributes.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] - public class MessagePackObjectAttribute : Attribute - { - public bool KeyAsPropertyName { get; private set; } - - public MessagePackObjectAttribute(bool keyAsPropertyName = false) - { - this.KeyAsPropertyName = keyAsPropertyName; - } - } - - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] - public class KeyAttribute : Attribute - { - public int? IntKey { get; private set; } - - public string StringKey { get; private set; } - - public KeyAttribute(int x) - { - this.IntKey = x; - } - - public KeyAttribute(string x) - { - this.StringKey = x; - } - } - - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] - public class IgnoreMemberAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] - public class UnionAttribute : Attribute - { - /// - /// Gets the distinguishing value that identifies a particular subtype. - /// - public int Key { get; private set; } - - /// - /// Gets the derived or implementing type. - /// - public Type SubType { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - /// The distinguishing value that identifies a particular subtype. - /// The derived or implementing type. - public UnionAttribute(int key, Type subType) - { - this.Key = key; - this.SubType = subType; - } - - /// - /// Initializes a new instance of the class. - /// - /// The distinguishing value that identifies a particular subtype. - /// The full name (should be assembly qualified) of the derived or implementing type. - public UnionAttribute(int key, string subType) - { - this.Key = key; - this.SubType = Type.GetType(subType, throwOnError: true); - } - } - - [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = true)] - public class SerializationConstructorAttribute : Attribute - { - } - - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] - public class MessagePackFormatterAttribute : Attribute - { - public Type FormatterType { get; private set; } - - public object[] Arguments { get; private set; } - - public MessagePackFormatterAttribute(Type formatterType) - { - this.FormatterType = formatterType; - } - - public MessagePackFormatterAttribute(Type formatterType, params object[] arguments) - { - this.FormatterType = formatterType; - this.Arguments = arguments; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/Attributes.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/Attributes.cs.meta deleted file mode 100644 index c834474..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/Attributes.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f684d4f03d4f86149990459d3054e2af -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs deleted file mode 100644 index 3b1daf4..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack -{ - public interface IMessagePackSerializationCallbackReceiver - { - void OnBeforeSerialize(); - - void OnAfterDeserialize(); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs.meta deleted file mode 100644 index 94f7b2e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/IMessagePackSerializationCallbackReceiver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b1714a0e4e8a7354e90f52000abdddd9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/MessagePack.Annotations.asmdef b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/MessagePack.Annotations.asmdef deleted file mode 100644 index e39d52d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/MessagePack.Annotations.asmdef +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "MessagePack.Annotations" -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/MessagePack.Annotations.asmdef.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/MessagePack.Annotations.asmdef.meta deleted file mode 100644 index bb24759..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Annotations/MessagePack.Annotations.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 5a46ad82eac024e4fbb6a0516a5def17 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BitOperations.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BitOperations.cs deleted file mode 100644 index 09b2ca0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BitOperations.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -// - -#if !NETCOREAPP - -using System.Runtime.CompilerServices; - -// Some routines inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson: -// http://graphics.stanford.edu/~seander/bithacks.html - -namespace System.Numerics -{ - /// - /// Utility methods for intrinsic bit-twiddling operations. - /// The methods use hardware intrinsics when available on the underlying platform, - /// otherwise they use optimized software fallbacks. - /// - internal static class BitOperations - { - /// - /// Rotates the specified value left by the specified number of bits. - /// Similar in behavior to the x86 instruction ROL. - /// - /// The value to rotate. - /// The number of bits to rotate by. - /// Any value outside the range [0..31] is treated as congruent mod 32. - /// The rotated value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint RotateLeft(uint value, int offset) - => (value << offset) | (value >> (32 - offset)); - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BitOperations.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BitOperations.cs.meta deleted file mode 100644 index 3f0e5b5..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BitOperations.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9b03a72c1f30f7a4f92f859479703d3c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BufferWriter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BufferWriter.cs deleted file mode 100644 index eba48fb..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BufferWriter.cs +++ /dev/null @@ -1,260 +0,0 @@ -// // We want to keep this file as-is since it's shared with other repos. - -// Copyright (c) .NET Foundation. All rights reserved. -// Copyright (c) Andrew Arnott. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace MessagePack -{ - /// - /// A fast access struct that wraps . - /// - internal ref struct BufferWriter - { - /// - /// The underlying . - /// - private IBufferWriter _output; - - /// - /// The result of the last call to , less any bytes already "consumed" with . - /// Backing field for the property. - /// - private Span _span; - - /// - /// The result of the last call to , less any bytes already "consumed" with . - /// - private ArraySegment _segment; - - /// - /// The number of uncommitted bytes (all the calls to since the last call to ). - /// - private int _buffered; - - /// - /// The total number of bytes written with this writer. - /// Backing field for the property. - /// - private long _bytesCommitted; - - private SequencePool _sequencePool; - - private SequencePool.Rental _rental; - - /// - /// Initializes a new instance of the struct. - /// - /// The to be wrapped. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public BufferWriter(IBufferWriter output) - { - _buffered = 0; - _bytesCommitted = 0; - _output = output ?? throw new ArgumentNullException(nameof(output)); - - _sequencePool = default; - _rental = default; - - var memory = _output.GetMemoryCheckResult(); - MemoryMarshal.TryGetArray(memory, out _segment); - _span = memory.Span; - } - - /// - /// Initializes a new instance of the struct. - /// - /// The pool from which to draw an if required.. - /// An array to start with so we can avoid accessing the if possible. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal BufferWriter(SequencePool sequencePool, byte[] array) - { - _buffered = 0; - _bytesCommitted = 0; - _sequencePool = sequencePool ?? throw new ArgumentNullException(nameof(sequencePool)); - _rental = default; - _output = null; - - _segment = new ArraySegment(array); - _span = _segment.AsSpan(); - } - - /// - /// Gets the result of the last call to . - /// - public Span Span => _span; - - /// - /// Gets the total number of bytes written with this writer. - /// - public long BytesCommitted => _bytesCommitted; - - /// - /// Gets the underlying this instance. - /// - internal IBufferWriter UnderlyingWriter => _output; - - internal SequencePool.Rental SequenceRental => _rental; - - public Span GetSpan(int sizeHint) - { - Ensure(sizeHint); - return this.Span; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ref byte GetPointer(int sizeHint) - { - Ensure(sizeHint); - - if (_segment.Array != null) - { - return ref _segment.Array[_segment.Offset + _buffered]; - } - else - { - return ref _span.GetPinnableReference(); - } - } - - /// - /// Calls on the underlying writer - /// with the number of uncommitted bytes. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Commit() - { - var buffered = _buffered; - if (buffered > 0) - { - this.MigrateToSequence(); - - _bytesCommitted += buffered; - _buffered = 0; - _output.Advance(buffered); - _span = default; - } - } - - /// - /// Used to indicate that part of the buffer has been written to. - /// - /// The number of bytes written to. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Advance(int count) - { - _buffered += count; - _span = _span.Slice(count); - } - - /// - /// Copies the caller's buffer into this writer and calls with the length of the source buffer. - /// - /// The buffer to copy in. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(ReadOnlySpan source) - { - if (_span.Length >= source.Length) - { - source.CopyTo(_span); - Advance(source.Length); - } - else - { - WriteMultiBuffer(source); - } - } - - /// - /// Acquires a new buffer if necessary to ensure that some given number of bytes can be written to a single buffer. - /// - /// The number of bytes that must be allocated in a single buffer. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Ensure(int count = 1) - { - if (_span.Length < count) - { - EnsureMore(count); - } - } - - /// - /// Gets the span to the bytes written if they were never committed to the underlying buffer writer. - /// - /// - /// - internal bool TryGetUncommittedSpan(out ReadOnlySpan span) - { - if (this._sequencePool != null) - { - span = _segment.AsSpan(0, _buffered); - return true; - } - - span = default; - return false; - } - - /// - /// Gets a fresh span to write to, with an optional minimum size. - /// - /// The minimum size for the next requested buffer. - [MethodImpl(MethodImplOptions.NoInlining)] - private void EnsureMore(int count = 0) - { - if (_buffered > 0) - { - Commit(); - } - else - { - this.MigrateToSequence(); - } - - var memory = _output.GetMemoryCheckResult(count); - MemoryMarshal.TryGetArray(memory, out _segment); - _span = memory.Span; - } - - /// - /// Copies the caller's buffer into this writer, potentially across multiple buffers from the underlying writer. - /// - /// The buffer to copy into this writer. - private void WriteMultiBuffer(ReadOnlySpan source) - { - int copiedBytes = 0; - int bytesLeftToCopy = source.Length; - while (bytesLeftToCopy > 0) - { - if (_span.Length == 0) - { - EnsureMore(); - } - - var writable = Math.Min(bytesLeftToCopy, _span.Length); - source.Slice(copiedBytes, writable).CopyTo(_span); - copiedBytes += writable; - bytesLeftToCopy -= writable; - Advance(writable); - } - } - - private void MigrateToSequence() - { - if (this._sequencePool != null) - { - // We were writing to our private scratch memory, so we have to copy it into the actual writer. - _rental = _sequencePool.Rent(); - _output = _rental.Value; - var realSpan = _output.GetSpan(_buffered); - _segment.AsSpan(0, _buffered).CopyTo(realSpan); - _sequencePool = null; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BufferWriter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BufferWriter.cs.meta deleted file mode 100644 index cb85fde..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/BufferWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2ed92c5d94108c44c93e31cd211ef1a6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionHeader.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionHeader.cs deleted file mode 100644 index 833e729..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionHeader.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack -{ -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - struct ExtensionHeader : IEquatable - { - public sbyte TypeCode { get; private set; } - - public uint Length { get; private set; } - - public ExtensionHeader(sbyte typeCode, uint length) - { - this.TypeCode = typeCode; - this.Length = length; - } - - public ExtensionHeader(sbyte typeCode, int length) - { - this.TypeCode = typeCode; - this.Length = (uint)length; - } - - public bool Equals(ExtensionHeader other) => this.TypeCode == other.TypeCode && this.Length == other.Length; - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionHeader.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionHeader.cs.meta deleted file mode 100644 index 0b1db29..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionHeader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 27ccbf9800df8ad48be2d278e288b37e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionResult.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionResult.cs deleted file mode 100644 index 780d9bb..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionResult.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -namespace MessagePack -{ -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - struct ExtensionResult - { - public ExtensionResult(sbyte typeCode, Memory data) - { - this.TypeCode = typeCode; - this.Data = new ReadOnlySequence(data); - } - - public ExtensionResult(sbyte typeCode, ReadOnlySequence data) - { - this.TypeCode = typeCode; - this.Data = data; - } - - public sbyte TypeCode { get; private set; } - - public ReadOnlySequence Data { get; private set; } - - public ExtensionHeader Header => new ExtensionHeader(this.TypeCode, (uint)this.Data.Length); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionResult.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionResult.cs.meta deleted file mode 100644 index fc087a3..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ExtensionResult.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3e64fdfe376c995419f98e1384f33b3e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters.meta deleted file mode 100644 index 82405ae..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 419e470fd6919bd468e25bcf581e081b -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionFormatter.cs deleted file mode 100644 index 590719e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionFormatter.cs +++ /dev/null @@ -1,1333 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Linq; -using System.Runtime.InteropServices; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class ArrayFormatter : IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Length); - - for (int i = 0; i < value.Length; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, value[i], options); - } - } - } - - public T[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - var array = new T[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - array[i] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ByteMemoryFormatter : IMessagePackFormatter> - { - public static readonly ByteMemoryFormatter Instance = new ByteMemoryFormatter(); - - private ByteMemoryFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Memory value, MessagePackSerializerOptions options) - { - writer.Write(value.Span); - } - - public Memory Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes() is ReadOnlySequence bytes ? new Memory(bytes.ToArray()) : default; - } - } - - public sealed class ByteReadOnlyMemoryFormatter : IMessagePackFormatter> - { - public static readonly ByteReadOnlyMemoryFormatter Instance = new ByteReadOnlyMemoryFormatter(); - - private ByteReadOnlyMemoryFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, ReadOnlyMemory value, MessagePackSerializerOptions options) - { - writer.Write(value.Span); - } - - public ReadOnlyMemory Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes() is ReadOnlySequence bytes ? new ReadOnlyMemory(bytes.ToArray()) : default; - } - } - - public sealed class ByteReadOnlySequenceFormatter : IMessagePackFormatter> - { - public static readonly ByteReadOnlySequenceFormatter Instance = new ByteReadOnlySequenceFormatter(); - - private ByteReadOnlySequenceFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, ReadOnlySequence value, MessagePackSerializerOptions options) - { - writer.WriteBinHeader(checked((int)value.Length)); - foreach (ReadOnlyMemory segment in value) - { - writer.WriteRaw(segment.Span); - } - } - - public ReadOnlySequence Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes() is ReadOnlySequence bytes ? new ReadOnlySequence(bytes.ToArray()) : default; - } - } - - public sealed class ByteArraySegmentFormatter : IMessagePackFormatter> - { - public static readonly ByteArraySegmentFormatter Instance = new ByteArraySegmentFormatter(); - - private ByteArraySegmentFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, ArraySegment value, MessagePackSerializerOptions options) - { - if (value.Array == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value); - } - } - - public ArraySegment Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes() is ReadOnlySequence bytes ? new ArraySegment(bytes.ToArray()) : default; - } - } - - public sealed class MemoryFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Memory value, MessagePackSerializerOptions options) - { - var formatter = options.Resolver.GetFormatterWithVerify>(); - formatter.Serialize(ref writer, value, options); - } - - public Memory Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - - public sealed class ReadOnlyMemoryFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ReadOnlyMemory value, MessagePackSerializerOptions options) - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var span = value.Span; - writer.WriteArrayHeader(span.Length); - - for (int i = 0; i < span.Length; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, span[i], options); - } - } - - public ReadOnlyMemory Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - - public sealed class ReadOnlySequenceFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ReadOnlySequence value, MessagePackSerializerOptions options) - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(checked((int)value.Length)); - foreach (ReadOnlyMemory segment in value) - { - ReadOnlySpan span = segment.Span; - for (int i = 0; i < span.Length; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, span[i], options); - } - } - } - - public ReadOnlySequence Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return new ReadOnlySequence(options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options)); - } - } - - public sealed class ArraySegmentFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ArraySegment value, MessagePackSerializerOptions options) - { - if (value.Array == null) - { - writer.WriteNil(); - } - else - { - var formatter = options.Resolver.GetFormatterWithVerify>(); - formatter.Serialize(ref writer, value, options); - } - } - - public ArraySegment Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - T[] array = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - return new ArraySegment(array); - } - } - } - - // List is popular format, should avoid abstraction. - public sealed class ListFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, List value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var c = value.Count; - writer.WriteArrayHeader(c); - - for (int i = 0; i < c; i++) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, value[i], options); - } - } - } - - public List Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - var list = new List((int)len); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < len; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list.Add(formatter.Deserialize(ref reader, options)); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - } - - public abstract class CollectionFormatterBase : IMessagePackFormatter - where TCollection : IEnumerable - where TEnumerator : IEnumerator - { - public void Serialize(ref MessagePackWriter writer, TCollection value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - // Optimize iteration(array is fastest) - if (value is TElement[] array) - { - writer.WriteArrayHeader(array.Length); - - foreach (TElement item in array) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - else - { - // knows count or not. - var seqCount = this.GetCount(value); - if (seqCount != null) - { - writer.WriteArrayHeader(seqCount.Value); - - // Unity's foreach struct enumerator causes boxing so iterate manually. - using (var e = this.GetSourceEnumerator(value)) - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, e.Current, options); - } - } - } - else - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - var scratch = scratchRental.Value; - MessagePackWriter scratchWriter = writer.Clone(scratch); - var count = 0; - using (var e = this.GetSourceEnumerator(value)) - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - count++; - formatter.Serialize(ref scratchWriter, e.Current, options); - } - } - - scratchWriter.Flush(); - writer.WriteArrayHeader(count); - writer.WriteRaw(scratch.AsReadOnlySequence); - } - } - } - } - } - - public TCollection Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(TCollection); - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - - TIntermediate list = this.Create(len, options); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < len; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - this.Add(list, i, formatter.Deserialize(ref reader, options), options); - } - } - finally - { - reader.Depth--; - } - - return this.Complete(list); - } - } - - // abstraction for serialize - protected virtual int? GetCount(TCollection sequence) - { - var collection = sequence as ICollection; - if (collection != null) - { - return collection.Count; - } - else - { - var c2 = sequence as IReadOnlyCollection; - if (c2 != null) - { - return c2.Count; - } - } - - return null; - } - - // Some collections can use struct iterator, this is optimization path - protected abstract TEnumerator GetSourceEnumerator(TCollection source); - - // abstraction for deserialize - protected abstract TIntermediate Create(int count, MessagePackSerializerOptions options); - - protected abstract void Add(TIntermediate collection, int index, TElement value, MessagePackSerializerOptions options); - - protected abstract TCollection Complete(TIntermediate intermediateCollection); - } - - public abstract class CollectionFormatterBase : CollectionFormatterBase, TCollection> - where TCollection : IEnumerable - { - protected override IEnumerator GetSourceEnumerator(TCollection source) - { - return source.GetEnumerator(); - } - } - - public abstract class CollectionFormatterBase : CollectionFormatterBase - where TCollection : IEnumerable - { - protected sealed override TCollection Complete(TCollection intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class GenericCollectionFormatter : CollectionFormatterBase - where TCollection : ICollection, new() - { - protected override TCollection Create(int count, MessagePackSerializerOptions options) - { - return new TCollection(); - } - - protected override void Add(TCollection collection, int index, TElement value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - } - - public sealed class LinkedListFormatter : CollectionFormatterBase, LinkedList.Enumerator, LinkedList> - { - protected override void Add(LinkedList collection, int index, T value, MessagePackSerializerOptions options) - { - collection.AddLast(value); - } - - protected override LinkedList Complete(LinkedList intermediateCollection) - { - return intermediateCollection; - } - - protected override LinkedList Create(int count, MessagePackSerializerOptions options) - { - return new LinkedList(); - } - - protected override LinkedList.Enumerator GetSourceEnumerator(LinkedList source) - { - return source.GetEnumerator(); - } - } - - public sealed class QueueFormatter : CollectionFormatterBase, Queue.Enumerator, Queue> - { - protected override int? GetCount(Queue sequence) - { - return sequence.Count; - } - - protected override void Add(Queue collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Enqueue(value); - } - - protected override Queue Create(int count, MessagePackSerializerOptions options) - { - return new Queue(count); - } - - protected override Queue.Enumerator GetSourceEnumerator(Queue source) - { - return source.GetEnumerator(); - } - - protected override Queue Complete(Queue intermediateCollection) - { - return intermediateCollection; - } - } - - // should deserialize reverse order. - public sealed class StackFormatter : CollectionFormatterBase.Enumerator, Stack> - { - protected override int? GetCount(Stack sequence) - { - return sequence.Count; - } - - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - // add reverse - collection[collection.Length - 1 - index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override Stack.Enumerator GetSourceEnumerator(Stack source) - { - return source.GetEnumerator(); - } - - protected override Stack Complete(T[] intermediateCollection) - { - return new Stack(intermediateCollection); - } - } - - public sealed class HashSetFormatter : CollectionFormatterBase, HashSet.Enumerator, HashSet> - { - protected override int? GetCount(HashSet sequence) - { - return sequence.Count; - } - - protected override void Add(HashSet collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override HashSet Complete(HashSet intermediateCollection) - { - return intermediateCollection; - } - - protected override HashSet Create(int count, MessagePackSerializerOptions options) - { - return new HashSet(options.Security.GetEqualityComparer()); - } - - protected override HashSet.Enumerator GetSourceEnumerator(HashSet source) - { - return source.GetEnumerator(); - } - } - - public sealed class ReadOnlyCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override ReadOnlyCollection Complete(T[] intermediateCollection) - { - return new ReadOnlyCollection(intermediateCollection); - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - } - - [Obsolete("Use " + nameof(InterfaceListFormatter2) + " instead.")] - public sealed class InterfaceListFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override IList Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - [Obsolete("Use " + nameof(InterfaceCollectionFormatter2) + " instead.")] - public sealed class InterfaceCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override ICollection Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceListFormatter2 : CollectionFormatterBase, IList> - { - protected override void Add(List collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override List Create(int count, MessagePackSerializerOptions options) - { - return new List(count); - } - - protected override IList Complete(List intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceCollectionFormatter2 : CollectionFormatterBase, ICollection> - { - protected override void Add(List collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override List Create(int count, MessagePackSerializerOptions options) - { - return new List(count); - } - - protected override ICollection Complete(List intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceEnumerableFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override IEnumerable Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - // [Key, [Array]] - public sealed class InterfaceGroupingFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, IGrouping value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(2); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.Key, options); - options.Resolver.GetFormatterWithVerify>().Serialize(ref writer, value, options); - } - } - - public IGrouping Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid Grouping format."); - } - - options.Security.DepthStep(ref reader); - try - { - TKey key = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - IEnumerable value = options.Resolver.GetFormatterWithVerify>().Deserialize(ref reader, options); - return new Grouping(key, value); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class InterfaceLookupFormatter : CollectionFormatterBase, Dictionary>, ILookup> - { - protected override void Add(Dictionary> collection, int index, IGrouping value, MessagePackSerializerOptions options) - { - collection.Add(value.Key, value); - } - - protected override ILookup Complete(Dictionary> intermediateCollection) - { - return new Lookup(intermediateCollection); - } - - protected override Dictionary> Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary>(count); - } - } - - internal class Grouping : IGrouping - { - private readonly TKey key; - private readonly IEnumerable elements; - - public Grouping(TKey key, IEnumerable elements) - { - this.key = key; - this.elements = elements; - } - - public TKey Key - { - get - { - return this.key; - } - } - - public IEnumerator GetEnumerator() - { - return this.elements.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.elements.GetEnumerator(); - } - } - - internal class Lookup : ILookup - { - private readonly Dictionary> groupings; - - public Lookup(Dictionary> groupings) - { - this.groupings = groupings; - } - - public IEnumerable this[TKey key] - { - get - { - return this.groupings[key]; - } - } - - public int Count - { - get - { - return this.groupings.Count; - } - } - - public bool Contains(TKey key) - { - return this.groupings.ContainsKey(key); - } - - public IEnumerator> GetEnumerator() - { - return this.groupings.Values.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.groupings.Values.GetEnumerator(); - } - } - - /* NonGenerics */ - - public sealed class NonGenericListFormatter : IMessagePackFormatter - where T : class, IList, new() - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Count); - foreach (var item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(T); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadArrayHeader(); - - var list = new T(); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list.Add(formatter.Deserialize(ref reader, options)); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - - public sealed class NonGenericInterfaceCollectionFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NonGenericInterfaceCollectionFormatter(); - - private NonGenericInterfaceCollectionFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, ICollection value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Count); - foreach (var item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - - public ICollection Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(ICollection); - } - - var count = reader.ReadArrayHeader(); - if (count == 0) - { - return Array.Empty(); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var list = new object[count]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list[i] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - - public sealed class NonGenericInterfaceEnumerableFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NonGenericInterfaceEnumerableFormatter(); - - private NonGenericInterfaceEnumerableFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, IEnumerable value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - using (var scratchRental = SequencePool.Shared.Rent()) - { - var scratch = scratchRental.Value; - MessagePackWriter scratchWriter = writer.Clone(scratch); - var count = 0; - var e = value.GetEnumerator(); - try - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - count++; - formatter.Serialize(ref scratchWriter, e.Current, options); - } - } - finally - { - if (e is IDisposable d) - { - d.Dispose(); - } - } - - scratchWriter.Flush(); - writer.WriteArrayHeader(count); - writer.WriteRaw(scratch.AsReadOnlySequence); - } - } - - public IEnumerable Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(IEnumerable); - } - - var count = reader.ReadArrayHeader(); - if (count == 0) - { - return Array.Empty(); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var list = new object[count]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list[i] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - - public sealed class NonGenericInterfaceListFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NonGenericInterfaceListFormatter(); - - private NonGenericInterfaceListFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, IList value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(value.Count); - foreach (var item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - - public IList Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(IList); - } - - var count = reader.ReadArrayHeader(); - if (count == 0) - { - return Array.Empty(); - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var list = new object[count]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - list[i] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return list; - } - } - - public sealed class NonGenericDictionaryFormatter : IMessagePackFormatter - where T : class, IDictionary, new() - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteMapHeader(value.Count); - foreach (DictionaryEntry item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item.Key, options); - formatter.Serialize(ref writer, item.Value, options); - } - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadMapHeader(); - - var dict = CollectionHelpers.CreateHashCollection(count, options.Security.GetEqualityComparer()); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - var key = formatter.Deserialize(ref reader, options); - var value = formatter.Deserialize(ref reader, options); - dict.Add(key, value); - } - } - finally - { - reader.Depth--; - } - - return dict; - } - } - - public sealed class NonGenericInterfaceDictionaryFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NonGenericInterfaceDictionaryFormatter(); - - private NonGenericInterfaceDictionaryFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, IDictionary value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteMapHeader(value.Count); - foreach (DictionaryEntry item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item.Key, options); - formatter.Serialize(ref writer, item.Value, options); - } - } - - public IDictionary Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var count = reader.ReadMapHeader(); - - var dict = new Dictionary(count, options.Security.GetEqualityComparer()); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - var key = formatter.Deserialize(ref reader, options); - var value = formatter.Deserialize(ref reader, options); - dict.Add(key, value); - } - } - finally - { - reader.Depth--; - } - - return dict; - } - } - - public sealed class ObservableCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(ObservableCollection collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ObservableCollection Create(int count, MessagePackSerializerOptions options) - { - return new ObservableCollection(); - } - } - - public sealed class ReadOnlyObservableCollectionFormatter : CollectionFormatterBase, ReadOnlyObservableCollection> - { - protected override void Add(ObservableCollection collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ObservableCollection Create(int count, MessagePackSerializerOptions options) - { - return new ObservableCollection(); - } - - protected override ReadOnlyObservableCollection Complete(ObservableCollection intermediateCollection) - { - return new ReadOnlyObservableCollection(intermediateCollection); - } - } - - public sealed class InterfaceReadOnlyListFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override IReadOnlyList Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceReadOnlyCollectionFormatter : CollectionFormatterBase> - { - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - collection[index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override IReadOnlyCollection Complete(T[] intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class InterfaceSetFormatter : CollectionFormatterBase, ISet> - { - protected override void Add(HashSet collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ISet Complete(HashSet intermediateCollection) - { - return intermediateCollection; - } - - protected override HashSet Create(int count, MessagePackSerializerOptions options) - { - return new HashSet(options.Security.GetEqualityComparer()); - } - } - - public sealed class ConcurrentBagFormatter : CollectionFormatterBase> - { - protected override int? GetCount(ConcurrentBag sequence) - { - return sequence.Count; - } - - protected override void Add(ConcurrentBag collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Add(value); - } - - protected override ConcurrentBag Create(int count, MessagePackSerializerOptions options) - { - return new ConcurrentBag(); - } - } - - public sealed class ConcurrentQueueFormatter : CollectionFormatterBase> - { - protected override int? GetCount(ConcurrentQueue sequence) - { - return sequence.Count; - } - - protected override void Add(ConcurrentQueue collection, int index, T value, MessagePackSerializerOptions options) - { - collection.Enqueue(value); - } - - protected override ConcurrentQueue Create(int count, MessagePackSerializerOptions options) - { - return new ConcurrentQueue(); - } - } - - public sealed class ConcurrentStackFormatter : CollectionFormatterBase> - { - protected override int? GetCount(ConcurrentStack sequence) - { - return sequence.Count; - } - - protected override void Add(T[] collection, int index, T value, MessagePackSerializerOptions options) - { - // add reverse - collection[collection.Length - 1 - index] = value; - } - - protected override T[] Create(int count, MessagePackSerializerOptions options) - { - return count == 0 ? Array.Empty() : new T[count]; - } - - protected override ConcurrentStack Complete(T[] intermediateCollection) - { - return new ConcurrentStack(intermediateCollection); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionFormatter.cs.meta deleted file mode 100644 index 04788e8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d1185cc5503e9de47b44ccaf43b6d665 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionHelpers`2.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionHelpers`2.cs deleted file mode 100644 index bb1a3c6..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionHelpers`2.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; - -namespace MessagePack.Formatters -{ - /// - /// Provides general helpers for creating collections (including dictionaries). - /// - /// The concrete type of collection to create. - /// The type of equality comparer that we would hope to pass into the collection's constructor. - internal static class CollectionHelpers - where TCollection : new() - { - /// - /// The delegate that will create the collection, if the typical (int count, IEqualityComparer{T} equalityComparer) constructor was found. - /// - private static Func collectionCreator; - - /// - /// Initializes static members of the class. - /// - /// - /// Initializes a delegate that is optimized to create a collection of a given size and using the given equality comparer, if possible. - /// - static CollectionHelpers() - { - var ctor = typeof(TCollection).GetConstructor(new Type[] { typeof(int), typeof(TEqualityComparer) }); - if (ctor != null) - { - ParameterExpression param1 = Expression.Parameter(typeof(int), "count"); - ParameterExpression param2 = Expression.Parameter(typeof(TEqualityComparer), "equalityComparer"); - NewExpression body = Expression.New(ctor, param1, param2); - collectionCreator = Expression.Lambda>(body, param1, param2).Compile(); - } - } - - /// - /// Initializes a new instance of the collection. - /// - /// The number of elements the collection should be prepared to receive. - /// The equality comparer to initialize the collection with. - /// The newly initialized collection. - /// - /// Use of the and are a best effort. - /// If we can't find a constructor on the collection in the expected shape, we'll just instantiate the collection with its default constructor. - /// - internal static TCollection CreateHashCollection(int count, TEqualityComparer equalityComparer) => collectionCreator != null ? collectionCreator.Invoke(count, equalityComparer) : new TCollection(); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionHelpers`2.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionHelpers`2.cs.meta deleted file mode 100644 index 7a60cfa..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/CollectionHelpers`2.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7aad614464db2c44a86b3b012e69b609 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DateTimeFormatters.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DateTimeFormatters.cs deleted file mode 100644 index 06d2ef8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DateTimeFormatters.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - /// - /// Serialize by .NET native DateTime binary format. - /// - public sealed class NativeDateTimeFormatter : IMessagePackFormatter - { - public static readonly NativeDateTimeFormatter Instance = new NativeDateTimeFormatter(); - - public void Serialize(ref MessagePackWriter writer, DateTime value, MessagePackSerializerOptions options) - { - var dateData = value.ToBinary(); - writer.Write(dateData); - } - - public DateTime Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var dateData = reader.ReadInt64(); - return DateTime.FromBinary(dateData); - } - } - - public sealed class NativeDateTimeArrayFormatter : IMessagePackFormatter - { - public static readonly NativeDateTimeArrayFormatter Instance = new NativeDateTimeArrayFormatter(); - - public void Serialize(ref MessagePackWriter writer, DateTime[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i].ToBinary()); - } - } - } - - public DateTime[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new DateTime[len]; - for (int i = 0; i < array.Length; i++) - { - var dateData = reader.ReadInt64(); - array[i] = DateTime.FromBinary(dateData); - } - - return array; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DateTimeFormatters.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DateTimeFormatters.cs.meta deleted file mode 100644 index 2fadca5..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DateTimeFormatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 619edb2526be60b41b30abdd4f514a3b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DictionaryFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DictionaryFormatter.cs deleted file mode 100644 index 4b9347a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DictionaryFormatter.cs +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Reflection; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - // unfortunately, can't use IDictionary because supports IReadOnlyDictionary. - public abstract class DictionaryFormatterBase : IMessagePackFormatter - where TDictionary : IEnumerable> - where TEnumerator : IEnumerator> - { - public void Serialize(ref MessagePackWriter writer, TDictionary value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IFormatterResolver resolver = options.Resolver; - IMessagePackFormatter keyFormatter = resolver.GetFormatterWithVerify(); - IMessagePackFormatter valueFormatter = resolver.GetFormatterWithVerify(); - - int count; - { - var col = value as ICollection>; - if (col != null) - { - count = col.Count; - } - else - { - var col2 = value as IReadOnlyCollection>; - if (col2 != null) - { - count = col2.Count; - } - else - { - throw new MessagePackSerializationException("DictionaryFormatterBase's TDictionary supports only ICollection or IReadOnlyCollection"); - } - } - } - - writer.WriteMapHeader(count); - - TEnumerator e = this.GetSourceEnumerator(value); - try - { - while (e.MoveNext()) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - KeyValuePair item = e.Current; - keyFormatter.Serialize(ref writer, item.Key, options); - valueFormatter.Serialize(ref writer, item.Value, options); - } - } - finally - { - e.Dispose(); - } - } - } - - public TDictionary Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default(TDictionary); - } - else - { - IFormatterResolver resolver = options.Resolver; - IMessagePackFormatter keyFormatter = resolver.GetFormatterWithVerify(); - IMessagePackFormatter valueFormatter = resolver.GetFormatterWithVerify(); - - var len = reader.ReadMapHeader(); - - TIntermediate dict = this.Create(len, options); - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < len; i++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - TKey key = keyFormatter.Deserialize(ref reader, options); - - TValue value = valueFormatter.Deserialize(ref reader, options); - - this.Add(dict, i, key, value, options); - } - } - finally - { - reader.Depth--; - } - - return this.Complete(dict); - } - } - - // abstraction for serialize - - // Some collections can use struct iterator, this is optimization path - protected abstract TEnumerator GetSourceEnumerator(TDictionary source); - - // abstraction for deserialize - protected abstract TIntermediate Create(int count, MessagePackSerializerOptions options); - - protected abstract void Add(TIntermediate collection, int index, TKey key, TValue value, MessagePackSerializerOptions options); - - protected abstract TDictionary Complete(TIntermediate intermediateCollection); - } - - public abstract class DictionaryFormatterBase : DictionaryFormatterBase>, TDictionary> - where TDictionary : IEnumerable> - { - protected override IEnumerator> GetSourceEnumerator(TDictionary source) - { - return source.GetEnumerator(); - } - } - - public abstract class DictionaryFormatterBase : DictionaryFormatterBase - where TDictionary : IDictionary - { - protected override TDictionary Complete(TDictionary intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class DictionaryFormatter : DictionaryFormatterBase, Dictionary.Enumerator, Dictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override Dictionary Complete(Dictionary intermediateCollection) - { - return intermediateCollection; - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - - protected override Dictionary.Enumerator GetSourceEnumerator(Dictionary source) - { - return source.GetEnumerator(); - } - } - - public sealed class GenericDictionaryFormatter : DictionaryFormatterBase - where TDictionary : IDictionary, new() - { - protected override void Add(TDictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override TDictionary Create(int count, MessagePackSerializerOptions options) - { - return CollectionHelpers>.CreateHashCollection(count, options.Security.GetEqualityComparer()); - } - } - - public sealed class InterfaceDictionaryFormatter : DictionaryFormatterBase, IDictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - - protected override IDictionary Complete(Dictionary intermediateCollection) - { - return intermediateCollection; - } - } - - public sealed class SortedListFormatter : DictionaryFormatterBase> - { - protected override void Add(SortedList collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override SortedList Create(int count, MessagePackSerializerOptions options) - { - return new SortedList(count); - } - } - - public sealed class SortedDictionaryFormatter : DictionaryFormatterBase, SortedDictionary.Enumerator, SortedDictionary> - { - protected override void Add(SortedDictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override SortedDictionary Complete(SortedDictionary intermediateCollection) - { - return intermediateCollection; - } - - protected override SortedDictionary Create(int count, MessagePackSerializerOptions options) - { - return new SortedDictionary(); - } - - protected override SortedDictionary.Enumerator GetSourceEnumerator(SortedDictionary source) - { - return source.GetEnumerator(); - } - } - - public sealed class ReadOnlyDictionaryFormatter : DictionaryFormatterBase, ReadOnlyDictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override ReadOnlyDictionary Complete(Dictionary intermediateCollection) - { - return new ReadOnlyDictionary(intermediateCollection); - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - } - - public sealed class InterfaceReadOnlyDictionaryFormatter : DictionaryFormatterBase, IReadOnlyDictionary> - { - protected override void Add(Dictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.Add(key, value); - } - - protected override IReadOnlyDictionary Complete(Dictionary intermediateCollection) - { - return intermediateCollection; - } - - protected override Dictionary Create(int count, MessagePackSerializerOptions options) - { - return new Dictionary(count, options.Security.GetEqualityComparer()); - } - } - - public sealed class ConcurrentDictionaryFormatter : DictionaryFormatterBase> - { - protected override void Add(ConcurrentDictionary collection, int index, TKey key, TValue value, MessagePackSerializerOptions options) - { - collection.TryAdd(key, value); - } - - protected override ConcurrentDictionary Create(int count, MessagePackSerializerOptions options) - { - // concurrent dictionary can't access defaultConcurrecyLevel so does not use count overload. - return new ConcurrentDictionary(options.Security.GetEqualityComparer()); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DictionaryFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DictionaryFormatter.cs.meta deleted file mode 100644 index 593fcfa..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DictionaryFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: abfb83d1822bbfc409f1f182e365e8ea -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs deleted file mode 100644 index f7bd971..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; -using System.Reflection; - -namespace MessagePack.Formatters -{ - /// - /// This formatter can serialize any value whose static type is - /// for which another resolver can provide a formatter for the runtime type. - /// Its deserialization is limited to forwarding all calls to the . - /// - public sealed class DynamicObjectTypeFallbackFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new DynamicObjectTypeFallbackFormatter(); - - private delegate void SerializeMethod(object dynamicFormatter, ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); - - private static readonly Internal.ThreadsafeTypeKeyHashTable SerializerDelegates = new Internal.ThreadsafeTypeKeyHashTable(); - - private DynamicObjectTypeFallbackFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options) - { - if (value is null) - { - writer.WriteNil(); - return; - } - - Type type = value.GetType(); - TypeInfo ti = type.GetTypeInfo(); - - if (type == typeof(object)) - { - // serialize to empty map - writer.WriteMapHeader(0); - return; - } - - if (PrimitiveObjectFormatter.IsSupportedType(type, ti, value)) - { - if (!(value is System.Collections.IDictionary || value is System.Collections.ICollection)) - { - PrimitiveObjectFormatter.Instance.Serialize(ref writer, value, options); - return; - } - } - - object formatter = options.Resolver.GetFormatterDynamicWithVerify(type); - if (!SerializerDelegates.TryGetValue(type, out SerializeMethod serializerDelegate)) - { - lock (SerializerDelegates) - { - if (!SerializerDelegates.TryGetValue(type, out serializerDelegate)) - { - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter"); - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "value"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodInfo serializeMethodInfo = formatterType.GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - - MethodCallExpression body = Expression.Call( - Expression.Convert(param0, formatterType), - serializeMethodInfo, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3); - - serializerDelegate = Expression.Lambda(body, param0, param1, param2, param3).Compile(); - - SerializerDelegates.TryAdd(type, serializerDelegate); - } - } - } - - serializerDelegate(formatter, ref writer, value, options); - } - - public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return PrimitiveObjectFormatter.Instance.Deserialize(ref reader, options); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs.meta deleted file mode 100644 index 81f1c93..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/DynamicObjectTypeFallbackFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 13f8970ea4cf5834783e2cf34116798a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/EnumAsStringFormatter`1.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/EnumAsStringFormatter`1.cs deleted file mode 100644 index 9333966..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/EnumAsStringFormatter`1.cs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.Serialization; - -namespace MessagePack.Formatters -{ - // Note:This implementation is 'not' fastest, should more improve. - public sealed class EnumAsStringFormatter : IMessagePackFormatter - { - private readonly IReadOnlyDictionary nameValueMapping; - private readonly IReadOnlyDictionary valueNameMapping; - private readonly IReadOnlyDictionary clrToSerializationName; - private readonly IReadOnlyDictionary serializationToClrName; - private readonly bool enumMemberOverridesPresent; - private readonly bool isFlags; - - public EnumAsStringFormatter() - { - this.isFlags = typeof(T).GetCustomAttribute() is object; - - var fields = typeof(T).GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static); - var nameValueMapping = new Dictionary(fields.Length); - var valueNameMapping = new Dictionary(); - Dictionary clrToSerializationName = null; - Dictionary serializationToClrName = null; - - foreach (FieldInfo enumValueMember in fields) - { - string name = enumValueMember.Name; - T value = (T)enumValueMember.GetValue(null); - - // Consider the case where the serialized form of the enum value is overridden via an attribute. - var attribute = enumValueMember.GetCustomAttribute(); - if (attribute?.IsValueSetExplicitly ?? false) - { - clrToSerializationName = clrToSerializationName ?? new Dictionary(); - serializationToClrName = serializationToClrName ?? new Dictionary(); - - clrToSerializationName.Add(name, attribute.Value); - serializationToClrName.Add(attribute.Value, name); - - name = attribute.Value; - this.enumMemberOverridesPresent = true; - } - - nameValueMapping[name] = value; - valueNameMapping[value] = name; - } - - this.nameValueMapping = nameValueMapping; - this.valueNameMapping = valueNameMapping; - this.clrToSerializationName = clrToSerializationName; - this.serializationToClrName = serializationToClrName; - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - // Enum.ToString() is slow, so avoid it when we can. - if (!this.valueNameMapping.TryGetValue(value, out string valueString)) - { - // fallback for flags, values with no name, etc - valueString = this.GetSerializedNames(value.ToString()); - } - - writer.Write(valueString); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - string name = reader.ReadString(); - - // Avoid Enum.Parse when we can because it is too slow. - if (!this.nameValueMapping.TryGetValue(name, out T value)) - { - value = (T)Enum.Parse(typeof(T), this.GetClrNames(name)); - } - - return value; - } - - private string GetClrNames(string serializedNames) - { - if (this.enumMemberOverridesPresent && this.isFlags && serializedNames.IndexOf(", ", StringComparison.Ordinal) >= 0) - { - return Translate(serializedNames, this.serializationToClrName); - } - - // We don't need to consider the trivial case of no commas because our caller would have found that in the lookup table and not called us. - return serializedNames; - } - - private string GetSerializedNames(string clrNames) - { - if (this.enumMemberOverridesPresent && this.isFlags && clrNames.IndexOf(", ", StringComparison.Ordinal) >= 0) - { - return Translate(clrNames, this.clrToSerializationName); - } - - // We don't need to consider the trivial case of no commas because our caller would have found that in the lookup table and not called us. - return clrNames; - } - - private static string Translate(string items, IReadOnlyDictionary mapping) - { - string[] elements = items.Split(','); - - for (int i = 0; i < elements.Length; i++) - { - // Trim the leading space if there is one (due to the delimiter being ", "). - if (i > 0 && elements[i].Length > 0 && elements[i][0] == ' ') - { - elements[i] = elements[i].Substring(1); - } - - if (mapping.TryGetValue(elements[i], out string substituteValue)) - { - elements[i] = substituteValue; - } - } - - return string.Join(", ", elements); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/EnumAsStringFormatter`1.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/EnumAsStringFormatter`1.cs.meta deleted file mode 100644 index e4a0bf9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/EnumAsStringFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4dc4ef7e6eaadef48b04d66cb80b5697 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/ExpandoObjectFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/ExpandoObjectFormatter.cs deleted file mode 100644 index a0d9c6c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/ExpandoObjectFormatter.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Collections.Generic; -using System.Dynamic; - -namespace MessagePack.Formatters -{ - public class ExpandoObjectFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new ExpandoObjectFormatter(); - - private ExpandoObjectFormatter() - { - } - - public ExpandoObject Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - var result = new ExpandoObject(); - int count = reader.ReadMapHeader(); - if (count > 0) - { - IFormatterResolver resolver = options.Resolver; - IMessagePackFormatter keyFormatter = resolver.GetFormatterWithVerify(); - IMessagePackFormatter valueFormatter = resolver.GetFormatterWithVerify(); - IDictionary dictionary = result; - - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < count; i++) - { - string key = keyFormatter.Deserialize(ref reader, options); - object value = valueFormatter.Deserialize(ref reader, options); - dictionary.Add(key, value); - } - } - finally - { - reader.Depth--; - } - } - - return result; - } - - public void Serialize(ref MessagePackWriter writer, ExpandoObject value, MessagePackSerializerOptions options) - { - var dict = (IDictionary)value; - var keyFormatter = options.Resolver.GetFormatterWithVerify(); - var valueFormatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteMapHeader(dict.Count); - foreach (var item in dict) - { - keyFormatter.Serialize(ref writer, item.Key, options); - valueFormatter.Serialize(ref writer, item.Value, options); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/ExpandoObjectFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/ExpandoObjectFormatter.cs.meta deleted file mode 100644 index 8d922b0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/ExpandoObjectFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3f013651a80f23245b9fe0ca2db89012 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/GenericEnumFormatter`1.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/GenericEnumFormatter`1.cs deleted file mode 100644 index 02c64fa..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/GenericEnumFormatter`1.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.CompilerServices; - -namespace MessagePack.Formatters -{ - public sealed class GenericEnumFormatter : IMessagePackFormatter - where T : Enum - { - private delegate void EnumSerialize(ref MessagePackWriter writer, ref T value); - - private delegate T EnumDeserialize(ref MessagePackReader reader); - - private readonly EnumSerialize serializer; - private readonly EnumDeserialize deserializer; - - public GenericEnumFormatter() - { - var underlyingType = typeof(T).GetEnumUnderlyingType(); - switch (Type.GetTypeCode(underlyingType)) - { -#pragma warning disable SA1107 // Avoid multiple statements on same line. - case TypeCode.Byte: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadByte(); return Unsafe.As(ref v); }; - break; - case TypeCode.Int16: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadInt16(); return Unsafe.As(ref v); }; - break; - case TypeCode.Int32: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadInt32(); return Unsafe.As(ref v); }; - break; - case TypeCode.Int64: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadInt64(); return Unsafe.As(ref v); }; - break; - case TypeCode.SByte: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadSByte(); return Unsafe.As(ref v); }; - break; - case TypeCode.UInt16: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadUInt16(); return Unsafe.As(ref v); }; - break; - case TypeCode.UInt32: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadUInt32(); return Unsafe.As(ref v); }; - break; - case TypeCode.UInt64: - serializer = (ref MessagePackWriter writer, ref T value) => writer.Write(Unsafe.As(ref value)); - deserializer = (ref MessagePackReader reader) => { var v = reader.ReadUInt64(); return Unsafe.As(ref v); }; - break; - default: - break; -#pragma warning restore SA1107 // Avoid multiple statements on same line. - } - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - serializer(ref writer, ref value); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return deserializer(ref reader); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/GenericEnumFormatter`1.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/GenericEnumFormatter`1.cs.meta deleted file mode 100644 index e8d3c5e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/GenericEnumFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 16ee992e15116754bae00d06d3968ec1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IMessagePackFormatter`1.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IMessagePackFormatter`1.cs deleted file mode 100644 index 510d2d1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IMessagePackFormatter`1.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Buffers; -using System.ComponentModel; - -namespace MessagePack.Formatters -{ -#pragma warning disable SA1649 // File name should match first type name - /// - /// A base interface for so that all generic implementations - /// can be detected by a common base type. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public interface IMessagePackFormatter - { - } -#pragma warning restore SA1649 // File name should match first type name - - /// - /// The contract for serialization of some specific type. - /// - /// The type to be serialized or deserialized. - public interface IMessagePackFormatter : IMessagePackFormatter - { - /// - /// Serializes a value. - /// - /// The writer to use when serializing the value. - /// The value to be serialized. - /// The serialization settings to use, including the resolver to use to obtain formatters for types that make up the composite type . - void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - - /// - /// Deserializes a value. - /// - /// The reader to deserialize from. - /// The serialization settings to use, including the resolver to use to obtain formatters for types that make up the composite type . - /// The deserialized value. - T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IMessagePackFormatter`1.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IMessagePackFormatter`1.cs.meta deleted file mode 100644 index 611109a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IMessagePackFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 88421097d73e1de479d2004c6c23d2e1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IgnoreFormatter`1.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IgnoreFormatter`1.cs deleted file mode 100644 index 12e3857..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IgnoreFormatter`1.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Buffers; - -namespace MessagePack.Formatters -{ - public sealed class IgnoreFormatter : IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - reader.Skip(); - return default(T); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IgnoreFormatter`1.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IgnoreFormatter`1.cs.meta deleted file mode 100644 index 01f517d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/IgnoreFormatter`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8916acfe5213bf940913b28c051e8231 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs deleted file mode 100644 index dfeb9d9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Text; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - /* multi dimensional array serialize to [i, j, [seq]] */ - - public sealed class TwoDimensionalArrayFormatter : IMessagePackFormatter - { - private const int ArrayLength = 3; - - public void Serialize(ref MessagePackWriter writer, T[,] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var i = value.GetLength(0); - var j = value.GetLength(1); - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(ArrayLength); - writer.Write(i); - writer.Write(j); - - writer.WriteArrayHeader(value.Length); - foreach (T item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - } - - public T[,] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - if (len != ArrayLength) - { - throw new MessagePackSerializationException("Invalid T[,] format"); - } - - var iLength = reader.ReadInt32(); - var jLength = reader.ReadInt32(); - var maxLen = reader.ReadArrayHeader(); - - var array = new T[iLength, jLength]; - - var i = 0; - var j = -1; - options.Security.DepthStep(ref reader); - try - { - for (int loop = 0; loop < maxLen; loop++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - if (j < jLength - 1) - { - j++; - } - else - { - j = 0; - i++; - } - - array[i, j] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class ThreeDimensionalArrayFormatter : IMessagePackFormatter - { - private const int ArrayLength = 4; - - public void Serialize(ref MessagePackWriter writer, T[,,] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var i = value.GetLength(0); - var j = value.GetLength(1); - var k = value.GetLength(2); - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(ArrayLength); - writer.Write(i); - writer.Write(j); - writer.Write(k); - - writer.WriteArrayHeader(value.Length); - foreach (T item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - } - - public T[,,] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - if (len != ArrayLength) - { - throw new MessagePackSerializationException("Invalid T[,,] format"); - } - - var iLength = reader.ReadInt32(); - var jLength = reader.ReadInt32(); - var kLength = reader.ReadInt32(); - var maxLen = reader.ReadArrayHeader(); - - var array = new T[iLength, jLength, kLength]; - - var i = 0; - var j = 0; - var k = -1; - options.Security.DepthStep(ref reader); - try - { - for (int loop = 0; loop < maxLen; loop++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - if (k < kLength - 1) - { - k++; - } - else if (j < jLength - 1) - { - k = 0; - j++; - } - else - { - k = 0; - j = 0; - i++; - } - - array[i, j, k] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } - - public sealed class FourDimensionalArrayFormatter : IMessagePackFormatter - { - private const int ArrayLength = 5; - - public void Serialize(ref MessagePackWriter writer, T[,,,] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var i = value.GetLength(0); - var j = value.GetLength(1); - var k = value.GetLength(2); - var l = value.GetLength(3); - - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - writer.WriteArrayHeader(ArrayLength); - writer.Write(i); - writer.Write(j); - writer.Write(k); - writer.Write(l); - - writer.WriteArrayHeader(value.Length); - foreach (T item in value) - { - writer.CancellationToken.ThrowIfCancellationRequested(); - formatter.Serialize(ref writer, item, options); - } - } - } - - public T[,,,] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - IMessagePackFormatter formatter = options.Resolver.GetFormatterWithVerify(); - - var len = reader.ReadArrayHeader(); - if (len != ArrayLength) - { - throw new MessagePackSerializationException("Invalid T[,,,] format"); - } - - var iLength = reader.ReadInt32(); - var jLength = reader.ReadInt32(); - var kLength = reader.ReadInt32(); - var lLength = reader.ReadInt32(); - var maxLen = reader.ReadArrayHeader(); - var array = new T[iLength, jLength, kLength, lLength]; - - var i = 0; - var j = 0; - var k = 0; - var l = -1; - options.Security.DepthStep(ref reader); - try - { - for (int loop = 0; loop < maxLen; loop++) - { - reader.CancellationToken.ThrowIfCancellationRequested(); - if (l < lLength - 1) - { - l++; - } - else if (k < kLength - 1) - { - l = 0; - k++; - } - else if (j < jLength - 1) - { - l = 0; - k = 0; - j++; - } - else - { - l = 0; - k = 0; - j = 0; - i++; - } - - array[i, j, k, l] = formatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs.meta deleted file mode 100644 index 0aee3e4..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/MultiDimensionalArrayFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ea25d9a859415b944a2932f414c2e353 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NilFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NilFormatter.cs deleted file mode 100644 index 61aad63..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NilFormatter.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack.Formatters -{ - public class NilFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NilFormatter(); - - private NilFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Nil value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public Nil Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadNil(); - } - } - - // NullableNil is same as Nil. - public class NullableNilFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new NullableNilFormatter(); - - private NullableNilFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Nil? value, MessagePackSerializerOptions options) - { - writer.WriteNil(); - } - - public Nil? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadNil(); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NilFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NilFormatter.cs.meta deleted file mode 100644 index e3bba6d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NilFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: cb4a59c3b8b4d144db65ac850daf0e53 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NullableFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NullableFormatter.cs deleted file mode 100644 index bba535a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NullableFormatter.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class NullableFormatter : IMessagePackFormatter - where T : struct - { - public void Serialize(ref MessagePackWriter writer, T? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - } - } - - public T? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - reader.ReadNil(); - return null; - } - else - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - } - - public sealed class StaticNullableFormatter : IMessagePackFormatter - where T : struct - { - private readonly IMessagePackFormatter underlyingFormatter; - - public StaticNullableFormatter(IMessagePackFormatter underlyingFormatter) - { - this.underlyingFormatter = underlyingFormatter; - } - - public void Serialize(ref MessagePackWriter writer, T? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - this.underlyingFormatter.Serialize(ref writer, value.Value, options); - } - } - - public T? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return this.underlyingFormatter.Deserialize(ref reader, options); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NullableFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NullableFormatter.cs.meta deleted file mode 100644 index a8bf3ac..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/NullableFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 05a403acf284b814abe1eabfbde39d1e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/PrimitiveObjectFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/PrimitiveObjectFormatter.cs deleted file mode 100644 index 7cf007e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/PrimitiveObjectFormatter.cs +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Net.Security; -using System.Reflection; - -namespace MessagePack.Formatters -{ - public class PrimitiveObjectFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new PrimitiveObjectFormatter(); - - private static readonly Dictionary TypeToJumpCode = new Dictionary() - { - // When adding types whose size exceeds 32-bits, add support in MessagePackSecurity.GetHashCollisionResistantEqualityComparer() - { typeof(Boolean), 0 }, - { typeof(Char), 1 }, - { typeof(SByte), 2 }, - { typeof(Byte), 3 }, - { typeof(Int16), 4 }, - { typeof(UInt16), 5 }, - { typeof(Int32), 6 }, - { typeof(UInt32), 7 }, - { typeof(Int64), 8 }, - { typeof(UInt64), 9 }, - { typeof(Single), 10 }, - { typeof(Double), 11 }, - { typeof(DateTime), 12 }, - { typeof(string), 13 }, - { typeof(byte[]), 14 }, - }; - - protected PrimitiveObjectFormatter() - { - } - - public static bool IsSupportedType(Type type, TypeInfo typeInfo, object value) - { - if (value == null) - { - return true; - } - - if (TypeToJumpCode.ContainsKey(type)) - { - return true; - } - - if (typeInfo.IsEnum) - { - return true; - } - - if (value is System.Collections.IDictionary) - { - return true; - } - - if (value is System.Collections.ICollection) - { - return true; - } - - return false; - } - - public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - Type t = value.GetType(); - - int code; - if (TypeToJumpCode.TryGetValue(t, out code)) - { - switch (code) - { - case 0: - writer.Write((bool)value); - return; - case 1: - writer.Write((char)value); - return; - case 2: - writer.WriteInt8((sbyte)value); - return; - case 3: - writer.WriteUInt8((byte)value); - return; - case 4: - writer.WriteInt16((Int16)value); - return; - case 5: - writer.WriteUInt16((UInt16)value); - return; - case 6: - writer.WriteInt32((Int32)value); - return; - case 7: - writer.WriteUInt32((UInt32)value); - return; - case 8: - writer.WriteInt64((Int64)value); - return; - case 9: - writer.WriteUInt64((UInt64)value); - return; - case 10: - writer.Write((Single)value); - return; - case 11: - writer.Write((double)value); - return; - case 12: - writer.Write((DateTime)value); - return; - case 13: - writer.Write((string)value); - return; - case 14: - writer.Write((byte[])value); - return; - default: - throw new MessagePackSerializationException("Not supported primitive object resolver. type:" + t.Name); - } - } - else - { -#if UNITY_2018_3_OR_NEWER && !NETFX_CORE - if (t.IsEnum) -#else - if (t.GetTypeInfo().IsEnum) -#endif - { - Type underlyingType = Enum.GetUnderlyingType(t); - var code2 = TypeToJumpCode[underlyingType]; - switch (code2) - { - case 2: - writer.WriteInt8((sbyte)value); - return; - case 3: - writer.WriteUInt8((byte)value); - return; - case 4: - writer.WriteInt16((Int16)value); - return; - case 5: - writer.WriteUInt16((UInt16)value); - return; - case 6: - writer.WriteInt32((Int32)value); - return; - case 7: - writer.WriteUInt32((UInt32)value); - return; - case 8: - writer.WriteInt64((Int64)value); - return; - case 9: - writer.WriteUInt64((UInt64)value); - return; - default: - break; - } - } - else if (value is System.Collections.IDictionary) - { - // check IDictionary first - var d = value as System.Collections.IDictionary; - writer.WriteMapHeader(d.Count); - foreach (System.Collections.DictionaryEntry item in d) - { - this.Serialize(ref writer, item.Key, options); - this.Serialize(ref writer, item.Value, options); - } - - return; - } - else if (value is System.Collections.ICollection) - { - var c = value as System.Collections.ICollection; - writer.WriteArrayHeader(c.Count); - foreach (var item in c) - { - this.Serialize(ref writer, item, options); - } - - return; - } - } - - throw new MessagePackSerializationException("Not supported primitive object resolver. type:" + t.Name); - } - - public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - MessagePackType type = reader.NextMessagePackType; - IFormatterResolver resolver = options.Resolver; - switch (type) - { - case MessagePackType.Integer: - var code = reader.NextCode; - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return reader.ReadSByte(); - } - else if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return reader.ReadByte(); - } - else if (code == MessagePackCode.Int8) - { - return reader.ReadSByte(); - } - else if (code == MessagePackCode.Int16) - { - return reader.ReadInt16(); - } - else if (code == MessagePackCode.Int32) - { - return reader.ReadInt32(); - } - else if (code == MessagePackCode.Int64) - { - return reader.ReadInt64(); - } - else if (code == MessagePackCode.UInt8) - { - return reader.ReadByte(); - } - else if (code == MessagePackCode.UInt16) - { - return reader.ReadUInt16(); - } - else if (code == MessagePackCode.UInt32) - { - return reader.ReadUInt32(); - } - else if (code == MessagePackCode.UInt64) - { - return reader.ReadUInt64(); - } - - throw new MessagePackSerializationException("Invalid primitive bytes."); - case MessagePackType.Boolean: - return reader.ReadBoolean(); - case MessagePackType.Float: - if (reader.NextCode == MessagePackCode.Float32) - { - return reader.ReadSingle(); - } - else - { - return reader.ReadDouble(); - } - - case MessagePackType.String: - return reader.ReadString(); - case MessagePackType.Binary: - // We must copy the sequence returned by ReadBytes since the reader's sequence is only valid during deserialization. - return reader.ReadBytes()?.ToArray(); - case MessagePackType.Extension: - ExtensionHeader ext = reader.ReadExtensionFormatHeader(); - if (ext.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime) - { - return reader.ReadDateTime(ext); - } - - throw new MessagePackSerializationException("Invalid primitive bytes."); - case MessagePackType.Array: - { - var length = reader.ReadArrayHeader(); - if (length == 0) - { - return Array.Empty(); - } - - IMessagePackFormatter objectFormatter = resolver.GetFormatter(); - var array = new object[length]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < length; i++) - { - array[i] = objectFormatter.Deserialize(ref reader, options); - } - } - finally - { - reader.Depth--; - } - - return array; - } - - case MessagePackType.Map: - { - var length = reader.ReadMapHeader(); - - options.Security.DepthStep(ref reader); - try - { - return this.DeserializeMap(ref reader, length, options); - } - finally - { - reader.Depth--; - } - } - - case MessagePackType.Nil: - reader.ReadNil(); - return null; - default: - throw new MessagePackSerializationException("Invalid primitive bytes."); - } - } - - protected virtual object DeserializeMap(ref MessagePackReader reader, int length, MessagePackSerializerOptions options) - { - IMessagePackFormatter objectFormatter = options.Resolver.GetFormatter(); - var dictionary = new Dictionary(length, options.Security.GetEqualityComparer()); - for (int i = 0; i < length; i++) - { - var key = objectFormatter.Deserialize(ref reader, options); - var value = objectFormatter.Deserialize(ref reader, options); - dictionary.Add(key, value); - } - - return dictionary; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/PrimitiveObjectFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/PrimitiveObjectFormatter.cs.meta deleted file mode 100644 index 132a4ab..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/PrimitiveObjectFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5e9c746624d882945a740f31fc8ebda9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/StandardClassLibraryFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/StandardClassLibraryFormatter.cs deleted file mode 100644 index a227aac..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/StandardClassLibraryFormatter.cs +++ /dev/null @@ -1,638 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using MessagePack.Internal; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - // NET40 -> BigInteger, Complex, Tuple - - // byte[] is special. represents bin type. - public sealed class ByteArrayFormatter : IMessagePackFormatter - { - public static readonly ByteArrayFormatter Instance = new ByteArrayFormatter(); - - private ByteArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, byte[] value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public byte[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBytes()?.ToArray(); - } - } - - public sealed class NullableStringFormatter : IMessagePackFormatter - { - public static readonly NullableStringFormatter Instance = new NullableStringFormatter(); - - private NullableStringFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, string value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public string Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadString(); - } - } - - public sealed class NullableStringArrayFormatter : IMessagePackFormatter - { - public static readonly NullableStringArrayFormatter Instance = new NullableStringArrayFormatter(); - - private NullableStringArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, String[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public String[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new String[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadString(); - } - - return array; - } - } - - public sealed class DecimalFormatter : IMessagePackFormatter - { - public static readonly DecimalFormatter Instance = new DecimalFormatter(); - - private DecimalFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, decimal value, MessagePackSerializerOptions options) - { - var dest = writer.GetSpan(MessagePackRange.MaxFixStringLength); - if (System.Buffers.Text.Utf8Formatter.TryFormat(value, dest.Slice(1), out var written)) - { - // write header - dest[0] = (byte)(MessagePackCode.MinFixStr | written); - writer.Advance(written + 1); - } - else - { - // reset writer's span previously acquired that does not use - writer.Advance(0); - writer.Write(value.ToString(CultureInfo.InvariantCulture)); - } - } - - public decimal Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (!(reader.ReadStringSequence() is ReadOnlySequence sequence)) - { - throw new MessagePackSerializationException(string.Format("Unexpected msgpack code {0} ({1}) encountered.", MessagePackCode.Nil, MessagePackCode.ToFormatName(MessagePackCode.Nil))); - } - - if (sequence.IsSingleSegment) - { - var span = sequence.First.Span; - if (System.Buffers.Text.Utf8Parser.TryParse(span, out decimal result, out var bytesConsumed)) - { - if (span.Length != bytesConsumed) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - return result; - } - } - else - { - // sequence.Length is not free - var seqLen = (int)sequence.Length; - if (seqLen < 128) - { - Span span = stackalloc byte[seqLen]; - sequence.CopyTo(span); - if (System.Buffers.Text.Utf8Parser.TryParse(span, out decimal result, out var bytesConsumed)) - { - if (seqLen != bytesConsumed) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - return result; - } - } - else - { - var rentArray = ArrayPool.Shared.Rent(seqLen); - try - { - sequence.CopyTo(rentArray); - if (System.Buffers.Text.Utf8Parser.TryParse(rentArray.AsSpan(0, seqLen), out decimal result, out var bytesConsumed)) - { - if (seqLen != bytesConsumed) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - return result; - } - } - finally - { - ArrayPool.Shared.Return(rentArray); - } - } - } - - throw new MessagePackSerializationException("Can't parse to decimal, input string was not in a correct format."); - } - } - - public sealed class TimeSpanFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new TimeSpanFormatter(); - - private TimeSpanFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, TimeSpan value, MessagePackSerializerOptions options) - { - writer.Write(value.Ticks); - return; - } - - public TimeSpan Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return new TimeSpan(reader.ReadInt64()); - } - } - - public sealed class DateTimeOffsetFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new DateTimeOffsetFormatter(); - - private DateTimeOffsetFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTimeOffset value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(new DateTime(value.Ticks, DateTimeKind.Utc)); // current ticks as is - writer.Write((short)value.Offset.TotalMinutes); // offset is normalized in minutes - return; - } - - public DateTimeOffset Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid DateTimeOffset format."); - } - - DateTime utc = reader.ReadDateTime(); - - var dtOffsetMinutes = reader.ReadInt16(); - - return new DateTimeOffset(utc.Ticks, TimeSpan.FromMinutes(dtOffsetMinutes)); - } - } - - public sealed class GuidFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new GuidFormatter(); - - private GuidFormatter() - { - } - - public unsafe void Serialize(ref MessagePackWriter writer, Guid value, MessagePackSerializerOptions options) - { - byte* pBytes = stackalloc byte[36]; - Span bytes = new Span(pBytes, 36); - new GuidBits(ref value).Write(bytes); - writer.WriteString(bytes); - } - - public Guid Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - ReadOnlySequence segment = reader.ReadStringSequence().Value; - if (segment.Length != 36) - { - throw new MessagePackSerializationException("Unexpected length of string."); - } - - GuidBits result; - if (segment.IsSingleSegment) - { - result = new GuidBits(segment.First.Span); - } - else - { - Span bytes = stackalloc byte[36]; - segment.CopyTo(bytes); - result = new GuidBits(bytes); - } - - return result.Value; - } - } - - public sealed class UriFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new UriFormatter(); - - private UriFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Uri value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.OriginalString); - } - } - - public Uri Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute); - } - } - } - - public sealed class VersionFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new VersionFormatter(); - - private VersionFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Version value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.ToString()); - } - } - - public Version Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return new Version(reader.ReadString()); - } - } - } - - public sealed class KeyValuePairFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, KeyValuePair value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Key, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - return; - } - - public KeyValuePair Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid KeyValuePair format."); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - TKey key = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - TValue value = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - return new KeyValuePair(key, value); - } - finally - { - reader.Depth--; - } - } - } - - public sealed class StringBuilderFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new StringBuilderFormatter(); - - private StringBuilderFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, StringBuilder value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.ToString()); - } - } - - public StringBuilder Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - return new StringBuilder(reader.ReadString()); - } - } - } - - public sealed class BitArrayFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new BitArrayFormatter(); - - private BitArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, BitArray value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - var len = value.Length; - writer.WriteArrayHeader(len); - for (int i = 0; i < len; i++) - { - writer.Write(value.Get(i)); - } - - return; - } - } - - public BitArray Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - var len = reader.ReadArrayHeader(); - - var array = new BitArray(len); - for (int i = 0; i < len; i++) - { - array[i] = reader.ReadBoolean(); - } - - return array; - } - } - } - - public sealed class BigIntegerFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new BigIntegerFormatter(); - - private BigIntegerFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, System.Numerics.BigInteger value, MessagePackSerializerOptions options) - { -#if NETCOREAPP - if (!writer.OldSpec) - { - // try to get bin8 buffer. - var span = writer.GetSpan(byte.MaxValue); - if (value.TryWriteBytes(span.Slice(2), out var written)) - { - span[0] = MessagePackCode.Bin8; - span[1] = (byte)written; - - writer.Advance(written + 2); - return; - } - else - { - // reset writer's span previously acquired that does not use - writer.Advance(0); - } - } -#endif - - writer.Write(value.ToByteArray()); - return; - } - - public System.Numerics.BigInteger Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - ReadOnlySequence bytes = reader.ReadBytes().Value; -#if NETCOREAPP - if (bytes.IsSingleSegment) - { - return new System.Numerics.BigInteger(bytes.First.Span); - } - else - { - byte[] bytesArray = ArrayPool.Shared.Rent((int)bytes.Length); - try - { - bytes.CopyTo(bytesArray); - return new System.Numerics.BigInteger(bytesArray.AsSpan(0, (int)bytes.Length)); - } - finally - { - ArrayPool.Shared.Return(bytesArray); - } - } -#else - return new System.Numerics.BigInteger(bytes.ToArray()); -#endif - } - } - - public sealed class ComplexFormatter : IMessagePackFormatter - { - public static readonly IMessagePackFormatter Instance = new ComplexFormatter(); - - private ComplexFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, System.Numerics.Complex value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(value.Real); - writer.Write(value.Imaginary); - return; - } - - public System.Numerics.Complex Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var count = reader.ReadArrayHeader(); - - if (count != 2) - { - throw new MessagePackSerializationException("Invalid Complex format."); - } - - var real = reader.ReadDouble(); - - var imaginary = reader.ReadDouble(); - - return new System.Numerics.Complex(real, imaginary); - } - } - - public sealed class LazyFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Lazy value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Value, options); - } - } - - public Lazy Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - else - { - options.Security.DepthStep(ref reader); - try - { - // deserialize immediately(no delay, because capture byte[] causes memory leak) - IFormatterResolver resolver = options.Resolver; - T v = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - return new Lazy(() => v); - } - finally - { - reader.Depth--; - } - } - } - } - - /// - /// Serializes any instance of by its value. - /// - /// The class itself or a derived type. - public sealed class TypeFormatter : IMessagePackFormatter - where T : Type - { - public static readonly IMessagePackFormatter Instance = new TypeFormatter(); - - private TypeFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (value is null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.AssemblyQualifiedName); - } - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - return (T)Type.GetType(reader.ReadString(), throwOnError: true); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/StandardClassLibraryFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/StandardClassLibraryFormatter.cs.meta deleted file mode 100644 index 222547a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/StandardClassLibraryFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ae4d882aeb27bc54e991d848a5683387 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs deleted file mode 100644 index 0d158a3..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !UNITY_2018_3_OR_NEWER - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text.RegularExpressions; -using MessagePack.Internal; - -namespace MessagePack.Formatters -{ -#pragma warning disable SA1649 // File name should match first type name - - /// - /// Force serialize object as typeless. - /// - public sealed class ForceTypelessFormatter : IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - TypelessFormatter.Instance.Serialize(ref writer, (object)value, options); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return (T)TypelessFormatter.Instance.Deserialize(ref reader, options); - } - } - -#pragma warning restore SA1649 // File name should match first type name - - /// - /// For `object` field that holds derived from `object` value, ex: var arr = new object[] { 1, "a", new Model() };. - /// - public sealed class TypelessFormatter : IMessagePackFormatter - { - private delegate void SerializeMethod(object dynamicContractlessFormatter, ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); - - private delegate object DeserializeMethod(object dynamicContractlessFormatter, ref MessagePackReader reader, MessagePackSerializerOptions options); - - /// - /// The singleton instance that can be used. - /// - public static readonly IMessagePackFormatter Instance = new TypelessFormatter(); - - private static readonly ThreadsafeTypeKeyHashTable Serializers = new ThreadsafeTypeKeyHashTable(); - private static readonly ThreadsafeTypeKeyHashTable Deserializers = new ThreadsafeTypeKeyHashTable(); - private static readonly ThreadsafeTypeKeyHashTable FullTypeNameCache = new ThreadsafeTypeKeyHashTable(); - private static readonly ThreadsafeTypeKeyHashTable ShortenedTypeNameCache = new ThreadsafeTypeKeyHashTable(); - private static readonly AsymmetricKeyHashTable, Type> TypeCache = new AsymmetricKeyHashTable, Type>(new StringArraySegmentByteAscymmetricEqualityComparer()); - - private static readonly HashSet UseBuiltinTypes = new HashSet - { - typeof(Boolean), - ////typeof(Char), - typeof(SByte), - typeof(Byte), - typeof(Int16), - typeof(UInt16), - typeof(Int32), - typeof(UInt32), - typeof(Int64), - typeof(UInt64), - typeof(Single), - typeof(Double), - typeof(string), - typeof(byte[]), - - // array should save their types. - ////typeof(Boolean[]), - ////typeof(Char[]), - ////typeof(SByte[]), - ////typeof(Int16[]), - ////typeof(UInt16[]), - ////typeof(Int32[]), - ////typeof(UInt32[]), - ////typeof(Int64[]), - ////typeof(UInt64[]), - ////typeof(Single[]), - ////typeof(Double[]), - ////typeof(string[]), - - typeof(Boolean?), - ////typeof(Char?), - typeof(SByte?), - typeof(Byte?), - typeof(Int16?), - typeof(UInt16?), - typeof(Int32?), - typeof(UInt32?), - typeof(Int64?), - typeof(UInt64?), - typeof(Single?), - typeof(Double?), - }; - - //ForceSizePrimitiveObjectResolver.Instance, - //ContractlessStandardResolverAllowPrivate.Instance); - - // mscorlib or System.Private.CoreLib - private static readonly bool IsMscorlib = typeof(int).AssemblyQualifiedName.Contains("mscorlib"); - - static TypelessFormatter() - { - Serializers.TryAdd(typeof(object), _ => (object p1, ref MessagePackWriter p2, object p3, MessagePackSerializerOptions p4) => { }); - Deserializers.TryAdd(typeof(object), _ => (object p1, ref MessagePackReader p2, MessagePackSerializerOptions p3) => new object()); - } - - private string BuildTypeName(Type type, MessagePackSerializerOptions options) - { - if (options.OmitAssemblyVersion) - { - string full = type.AssemblyQualifiedName; - - var shortened = MessagePackSerializerOptions.AssemblyNameVersionSelectorRegex.Replace(full, string.Empty); - if (Type.GetType(shortened, false) == null) - { - // if type cannot be found with shortened name - use full name - shortened = full; - } - - return shortened; - } - else - { - return type.AssemblyQualifiedName; - } - } - - public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - Type type = value.GetType(); - - byte[] typeName; - var typeNameCache = options.OmitAssemblyVersion ? ShortenedTypeNameCache : FullTypeNameCache; - if (!typeNameCache.TryGetValue(type, out typeName)) - { - TypeInfo ti = type.GetTypeInfo(); - if (ti.IsAnonymous() || UseBuiltinTypes.Contains(type)) - { - typeName = null; - } - else - { - typeName = StringEncoding.UTF8.GetBytes(this.BuildTypeName(type, options)); - } - - typeNameCache.TryAdd(type, typeName); - } - - if (typeName == null) - { - DynamicObjectTypeFallbackFormatter.Instance.Serialize(ref writer, value, options); - return; - } - - var formatter = options.Resolver.GetFormatterDynamicWithVerify(type); - - // don't use GetOrAdd for avoid closure capture. - if (!Serializers.TryGetValue(type, out SerializeMethod serializeMethod)) - { - // double check locking... - lock (Serializers) - { - if (!Serializers.TryGetValue(type, out serializeMethod)) - { - TypeInfo ti = type.GetTypeInfo(); - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter"); - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "value"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodInfo serializeMethodInfo = formatterType.GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - - MethodCallExpression body = Expression.Call( - Expression.Convert(param0, formatterType), - serializeMethodInfo, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3); - - serializeMethod = Expression.Lambda(body, param0, param1, param2, param3).Compile(); - - Serializers.TryAdd(type, serializeMethod); - } - } - } - - // mark will be written at the end, when size is known - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - scratchWriter.WriteString(typeName); - serializeMethod(formatter, ref scratchWriter, value, options); - scratchWriter.Flush(); - - // mark as extension with code 100 - writer.WriteExtensionFormat(new ExtensionResult((sbyte)ThisLibraryExtensionTypeCodes.TypelessFormatter, scratchRental.Value)); - } - } - - public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - if (reader.NextMessagePackType == MessagePackType.Extension) - { - MessagePackReader peekReader = reader.CreatePeekReader(); - ExtensionHeader ext = peekReader.ReadExtensionFormatHeader(); - if (ext.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter) - { - reader = peekReader; // commit the experimental read made earlier. - - // it has type name serialized - ReadOnlySequence typeName = reader.ReadStringSequence().Value; - ArraySegment typeNameArraySegment; - byte[] rented = null; - if (!typeName.IsSingleSegment || !MemoryMarshal.TryGetArray(typeName.First, out typeNameArraySegment)) - { - rented = ArrayPool.Shared.Rent((int)typeName.Length); - typeName.CopyTo(rented); - typeNameArraySegment = new ArraySegment(rented, 0, (int)typeName.Length); - } - - var result = this.DeserializeByTypeName(typeNameArraySegment, ref reader, options); - - if (rented != null) - { - ArrayPool.Shared.Return(rented); - } - - return result; - } - } - - // fallback - return DynamicObjectTypeFallbackFormatter.Instance.Deserialize(ref reader, options); - } - - /// - /// Does not support deserializing of anonymous types - /// Type should be covered by preceeding resolvers in complex/standard resolver. - /// - private object DeserializeByTypeName(ArraySegment typeName, ref MessagePackReader byteSequence, MessagePackSerializerOptions options) - { - // try get type with assembly name, throw if not found - Type type; - if (!TypeCache.TryGetValue(typeName, out type)) - { - var buffer = new byte[typeName.Count]; - Buffer.BlockCopy(typeName.Array, typeName.Offset, buffer, 0, buffer.Length); - var str = StringEncoding.UTF8.GetString(buffer); - type = options.LoadType(str); - if (type == null) - { - if (IsMscorlib && str.Contains("System.Private.CoreLib")) - { - str = str.Replace("System.Private.CoreLib", "mscorlib"); - type = Type.GetType(str, true); // throw - } - else if (!IsMscorlib && str.Contains("mscorlib")) - { - str = str.Replace("mscorlib", "System.Private.CoreLib"); - type = Type.GetType(str, true); // throw - } - else - { - type = Type.GetType(str, true); // re-throw - } - } - - TypeCache.TryAdd(buffer, type); - } - - options.ThrowIfDeserializingTypeIsDisallowed(type); - - var formatter = options.Resolver.GetFormatterDynamicWithVerify(type); - - if (!Deserializers.TryGetValue(type, out DeserializeMethod deserializeMethod)) - { - lock (Deserializers) - { - if (!Deserializers.TryGetValue(type, out deserializeMethod)) - { - TypeInfo ti = type.GetTypeInfo(); - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter"); - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackReader).MakeByRefType(), "reader"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodInfo deserializeMethodInfo = formatterType.GetRuntimeMethod("Deserialize", new[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - MethodCallExpression deserialize = Expression.Call( - Expression.Convert(param0, formatterType), - deserializeMethodInfo, - param1, - param2); - - Expression body = deserialize; - if (ti.IsValueType) - { - body = Expression.Convert(deserialize, typeof(object)); - } - - deserializeMethod = Expression.Lambda(body, param0, param1, param2).Compile(); - - Deserializers.TryAdd(type, deserializeMethod); - } - } - } - - return deserializeMethod(formatter, ref byteSequence, options); - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs.meta deleted file mode 100644 index f38eb5e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 368d3024351ce2e4abc42297e26c5108 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/UnsafeBinaryFormatters.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/UnsafeBinaryFormatters.cs deleted file mode 100644 index 56f5899..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/UnsafeBinaryFormatters.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class NativeGuidFormatter : IMessagePackFormatter - { - /// - /// Unsafe binary Guid formatter. this is only allowed on LittleEndian environment. - /// - public static readonly IMessagePackFormatter Instance = new NativeGuidFormatter(); - - private NativeGuidFormatter() - { - } - - /* Guid's underlying _a,...,_k field is sequential and same layout as .NET Framework and Mono(Unity). - * But target machines must be same endian so restrict only for little endian. */ - - public unsafe void Serialize(ref MessagePackWriter writer, Guid value, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeGuidFormatter only allows on little endian env."); - } - - var valueSpan = new ReadOnlySpan(&value, sizeof(Guid)); - writer.Write(valueSpan); - } - - public unsafe Guid Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeGuidFormatter only allows on little endian env."); - } - - ReadOnlySequence valueSequence = reader.ReadBytes().Value; - if (valueSequence.Length != sizeof(Guid)) - { - throw new MessagePackSerializationException("Invalid Guid Size."); - } - - Guid result; - var resultSpan = new Span(&result, sizeof(Guid)); - valueSequence.CopyTo(resultSpan); - return result; - } - } - - public sealed class NativeDecimalFormatter : IMessagePackFormatter - { - /// - /// Unsafe binary Decimal formatter. this is only allows on LittleEndian environment. - /// - public static readonly IMessagePackFormatter Instance = new NativeDecimalFormatter(); - - private NativeDecimalFormatter() - { - } - - /* decimal underlying "flags, hi, lo, mid" fields are sequential and same layuout with .NET Framework and Mono(Unity) - * But target machines must be same endian so restrict only for little endian. */ - - public unsafe void Serialize(ref MessagePackWriter writer, Decimal value, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeDecimalFormatter only allows on little endian env."); - } - - var valueSpan = new ReadOnlySpan(&value, sizeof(Decimal)); - writer.Write(valueSpan); - } - - public unsafe Decimal Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (!BitConverter.IsLittleEndian) - { - throw new InvalidOperationException("NativeDecimalFormatter only allows on little endian env."); - } - - ReadOnlySequence valueSequence = reader.ReadBytes().Value; - if (valueSequence.Length != sizeof(decimal)) - { - throw new MessagePackSerializationException("Invalid decimal Size."); - } - - decimal result; - var resultSpan = new Span(&result, sizeof(decimal)); - valueSequence.CopyTo(resultSpan); - return result; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/UnsafeBinaryFormatters.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/UnsafeBinaryFormatters.cs.meta deleted file mode 100644 index db6012c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Formatters/UnsafeBinaryFormatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0b4bd9957393761499af403a5ef7ebfa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/HashCode.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/HashCode.cs deleted file mode 100644 index 8d48c08..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/HashCode.cs +++ /dev/null @@ -1,481 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. -// - -/* - -The xxHash32 implementation is based on the code published by Yann Collet: -https://raw.githubusercontent.com/Cyan4973/xxHash/5c174cfa4e45a42f94082dc0d4539b39696afea1/xxhash.c - - xxHash - Fast Hash algorithm - Copyright (C) 2012-2016, Yann Collet - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - xxHash homepage: http://www.xxhash.com - - xxHash source repository : https://github.com/Cyan4973/xxHash - -*/ - -#if !NETCOREAPP - -using System.Collections.Generic; -using System.ComponentModel; -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Security.Cryptography; - -namespace System -{ - // xxHash32 is used for the hash code. - // https://github.com/Cyan4973/xxHash - - internal struct HashCode - { - private static readonly uint s_seed = GenerateGlobalSeed(); - - private const uint Prime1 = 2654435761U; - private const uint Prime2 = 2246822519U; - private const uint Prime3 = 3266489917U; - private const uint Prime4 = 668265263U; - private const uint Prime5 = 374761393U; - - private uint _v1, _v2, _v3, _v4; - private uint _queue1, _queue2, _queue3; - private uint _length; - - private static uint GenerateGlobalSeed() - { - var bytes = new byte[4]; - using (var rng = RandomNumberGenerator.Create()) - { - rng.GetBytes(bytes); - } - - return BitConverter.ToUInt32(bytes, 0); - } - - public static int Combine(T1 value1) - { - unchecked - { - // Provide a way of diffusing bits from something with a limited - // input hash space. For example, many enums only have a few - // possible hashes, only using the bottom few bits of the code. Some - // collections are built on the assumption that hashes are spread - // over a larger space, so diffusing the bits may help the - // collection work more efficiently. - - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 4; - - hash = QueueRound(hash, hc1); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 8; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 12; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - hash = QueueRound(hash, hc3); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 16; - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 20; - - hash = QueueRound(hash, hc5); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 24; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 28; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - hash = QueueRound(hash, hc7); - - hash = MixFinal(hash); - return (int)hash; - } - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) - { - unchecked - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - uint hc8 = (uint)(value8?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - v1 = Round(v1, hc5); - v2 = Round(v2, hc6); - v3 = Round(v3, hc7); - v4 = Round(v4, hc8); - - uint hash = MixState(v1, v2, v3, v4); - hash += 32; - - hash = MixFinal(hash); - return (int)hash; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) - { - unchecked - { - v1 = s_seed + Prime1 + Prime2; - v2 = s_seed + Prime2; - v3 = s_seed; - v4 = s_seed - Prime1; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint Round(uint hash, uint input) - { - unchecked - { - return BitOperations.RotateLeft(hash + input * Prime2, 13) * Prime1; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint QueueRound(uint hash, uint queuedValue) - { - unchecked - { - return BitOperations.RotateLeft(hash + queuedValue * Prime3, 17) * Prime4; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixState(uint v1, uint v2, uint v3, uint v4) - { - unchecked - { - return BitOperations.RotateLeft(v1, 1) + BitOperations.RotateLeft(v2, 7) + BitOperations.RotateLeft(v3, 12) + BitOperations.RotateLeft(v4, 18); - } - } - - private static uint MixEmptyState() - { - unchecked - { - return s_seed + Prime5; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixFinal(uint hash) - { - unchecked - { - hash ^= hash >> 15; - hash *= Prime2; - hash ^= hash >> 13; - hash *= Prime3; - hash ^= hash >> 16; - return hash; - } - } - - public void Add(T value) - { - Add(value?.GetHashCode() ?? 0); - } - - public void Add(T value, IEqualityComparer comparer) - { - Add(comparer != null ? comparer.GetHashCode(value) : (value?.GetHashCode() ?? 0)); - } - - private void Add(int value) - { - unchecked - { - // The original xxHash works as follows: - // 0. Initialize immediately. We can't do this in a struct (no - // default ctor). - // 1. Accumulate blocks of length 16 (4 uints) into 4 accumulators. - // 2. Accumulate remaining blocks of length 4 (1 uint) into the - // hash. - // 3. Accumulate remaining blocks of length 1 into the hash. - - // There is no need for #3 as this type only accepts ints. _queue1, - // _queue2 and _queue3 are basically a buffer so that when - // ToHashCode is called we can execute #2 correctly. - - // We need to initialize the xxHash32 state (_v1 to _v4) lazily (see - // #0) nd the last place that can be done if you look at the - // original code is just before the first block of 16 bytes is mixed - // in. The xxHash32 state is never used for streams containing fewer - // than 16 bytes. - - // To see what's really going on here, have a look at the Combine - // methods. - - uint val = (uint)value; - - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint previousLength = _length++; - uint position = previousLength % 4; - - // Switch can't be inlined. - - if (position == 0) - _queue1 = val; - else if (position == 1) - _queue2 = val; - else if (position == 2) - _queue3 = val; - else // position == 3 - { - if (previousLength == 3) - Initialize(out _v1, out _v2, out _v3, out _v4); - - _v1 = Round(_v1, _queue1); - _v2 = Round(_v2, _queue2); - _v3 = Round(_v3, _queue3); - _v4 = Round(_v4, val); - } - } - } - - public int ToHashCode() - { - unchecked - { - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint length = _length; - - // position refers to the *next* queue position in this method, so - // position == 1 means that _queue1 is populated; _queue2 would have - // been populated on the next call to Add. - uint position = length % 4; - - // If the length is less than 4, _v1 to _v4 don't contain anything - // yet. xxHash32 treats this differently. - - uint hash = length < 4 ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4); - - // _length is incremented once per Add(Int32) and is therefore 4 - // times too small (xxHash length is in bytes, not ints). - - hash += length * 4; - - // Mix what remains in the queue - - // Switch can't be inlined right now, so use as few branches as - // possible by manually excluding impossible scenarios (position > 1 - // is always false if position is not > 0). - if (position > 0) - { - hash = QueueRound(hash, _queue1); - if (position > 1) - { - hash = QueueRound(hash, _queue2); - if (position > 2) - hash = QueueRound(hash, _queue3); - } - } - - hash = MixFinal(hash); - return (int)hash; - } - } - -#pragma warning disable 0809 - // Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - // Disallowing GetHashCode and Equals is by design - - // * We decided to not override GetHashCode() to produce the hash code - // as this would be weird, both naming-wise as well as from a - // behavioral standpoint (GetHashCode() should return the object's - // hash code, not the one being computed). - - // * Even though ToHashCode() can be called safely multiple times on - // this implementation, it is not part of the contract. If the - // implementation has to change in the future we don't want to worry - // about people who might have incorrectly used this type. - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => throw new NotSupportedException(); - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => throw new NotSupportedException(); -#pragma warning restore 0809 - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/HashCode.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/HashCode.cs.meta deleted file mode 100644 index 2a50d75..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/HashCode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 56e9bfe9ee9b0354b8765ebefbac8d67 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/IFormatterResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/IFormatterResolver.cs deleted file mode 100644 index 7c5d000..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/IFormatterResolver.cs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.ExceptionServices; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack -{ - /// - /// Allows querying for a formatter for serializing or deserializing a particular . - /// - public interface IFormatterResolver - { - /// - /// Gets an instance that can serialize or deserialize some type . - /// - /// The type of value to be serialized or deserialized. - /// A formatter, if this resolver supplies one for type ; otherwise null. - IMessagePackFormatter GetFormatter(); - } - - public static class FormatterResolverExtensions - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IMessagePackFormatter GetFormatterWithVerify(this IFormatterResolver resolver) - { - if (resolver is null) - { - throw new ArgumentNullException(nameof(resolver)); - } - - IMessagePackFormatter formatter; - try - { - formatter = resolver.GetFormatter(); - } - catch (TypeInitializationException ex) - { - // The fact that we're using static constructors to initialize this is an internal detail. - // Rethrow the inner exception if there is one. - // Do it carefully so as to not stomp on the original callstack. - Throw(ex); - return default; // not reachable - } - - if (formatter == null) - { - Throw(typeof(T), resolver); - } - - return formatter; - } - - private static void Throw(TypeInitializationException ex) - { - ExceptionDispatchInfo.Capture(ex.InnerException ?? ex).Throw(); - } - - private static void Throw(Type t, IFormatterResolver resolver) - { - throw new FormatterNotRegisteredException(t.FullName + " is not registered in resolver: " + resolver.GetType()); - } - - private static readonly ThreadsafeTypeKeyHashTable> FormatterGetters = - new ThreadsafeTypeKeyHashTable>(); - - private static readonly MethodInfo GetFormatterRuntimeMethod = typeof(IFormatterResolver).GetRuntimeMethod(nameof(IFormatterResolver.GetFormatter), Type.EmptyTypes); - - public static object GetFormatterDynamic(this IFormatterResolver resolver, Type type) - { - if (resolver is null) - { - throw new ArgumentNullException(nameof(resolver)); - } - - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (!FormatterGetters.TryGetValue(type, out var formatterGetter)) - { - var genericMethod = GetFormatterRuntimeMethod.MakeGenericMethod(type); - var inputResolver = Expression.Parameter(typeof(IFormatterResolver), "inputResolver"); - formatterGetter = Expression.Lambda>( - Expression.Call(inputResolver, genericMethod), inputResolver).Compile(); - FormatterGetters.TryAdd(type, formatterGetter); - } - - return formatterGetter(resolver); - } - - internal static object GetFormatterDynamicWithVerify(this IFormatterResolver resolver, Type type) - { - var result = GetFormatterDynamic(resolver, type); - if (result == null) - { - Throw(type, resolver); - } - - return result; - } - } - - public class FormatterNotRegisteredException : MessagePackSerializationException - { - public FormatterNotRegisteredException(string message) - : base(message) - { - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/IFormatterResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/IFormatterResolver.cs.meta deleted file mode 100644 index b7f62ed..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/IFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ad1508639e1c32f489af46c74b5d3966 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal.meta deleted file mode 100644 index c0d56f4..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: b5d7c71f646ae9e4ea575ef78fc57bb8 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AsymmetricKeyHashTable.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AsymmetricKeyHashTable.cs deleted file mode 100644 index 4f0a2f1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AsymmetricKeyHashTable.cs +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !UNITY_2018_3_OR_NEWER - -using System; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Internal -{ - /* Safe for multiple-read, single-write. - * Add and Get Key is asymmetric. */ - - internal interface IAsymmetricEqualityComparer - { - int GetHashCode(TKey1 key1); - - int GetHashCode(TKey2 key2); - - bool Equals(TKey1 x, TKey1 y); // when used rehash - - bool Equals(TKey1 x, TKey2 y); // when used get - } - - internal class StringArraySegmentByteAscymmetricEqualityComparer : IAsymmetricEqualityComparer> - { - private static readonly bool Is32Bit = IntPtr.Size == 4; - - public bool Equals(byte[] x, byte[] y) - { - if (x.Length != y.Length) - { - return false; - } - - for (int i = 0; i < x.Length; i++) - { - if (x[i] != y[i]) - { - return false; - } - } - - return true; - } - - public bool Equals(byte[] x, ArraySegment y) - { - return x.AsSpan().SequenceEqual(y); - } - - public int GetHashCode(byte[] key1) - { - return this.GetHashCode(new ArraySegment(key1, 0, key1.Length)); - } - - public int GetHashCode(ArraySegment key2) - { - unchecked - { - if (Is32Bit) - { - return (int)FarmHash.Hash32(key2); - } - else - { - return (int)FarmHash.Hash64(key2); - } - } - } - } - - internal sealed class AsymmetricKeyHashTable - { - private Entry[] buckets; - private int size; // only use in writer lock - - private readonly object writerLock = new object(); - private readonly float loadFactor; - private readonly IAsymmetricEqualityComparer comparer; - - public AsymmetricKeyHashTable(IAsymmetricEqualityComparer comparer) - : this(4, 0.72f, comparer) - { - } - - public AsymmetricKeyHashTable(int capacity, float loadFactor, IAsymmetricEqualityComparer comparer) - { - var tableSize = CalculateCapacity(capacity, loadFactor); - this.buckets = new Entry[tableSize]; - this.loadFactor = loadFactor; - this.comparer = comparer; - } - - public TValue AddOrGet(TKey1 key1, Func valueFactory) - { - TValue v; - this.TryAddInternal(key1, valueFactory, out v); - return v; - } - - public bool TryAdd(TKey1 key, TValue value) - { - return this.TryAdd(key, _ => value); // closure capture - } - - public bool TryAdd(TKey1 key, Func valueFactory) - { - return this.TryAddInternal(key, valueFactory, out TValue _); - } - - private bool TryAddInternal(TKey1 key, Func valueFactory, out TValue resultingValue) - { - lock (this.writerLock) - { - var nextCapacity = CalculateCapacity(this.size + 1, this.loadFactor); - - if (this.buckets.Length < nextCapacity) - { - // rehash - var nextBucket = new Entry[nextCapacity]; - for (int i = 0; i < this.buckets.Length; i++) - { - Entry e = this.buckets[i]; - while (e != null) - { - var newEntry = new Entry { Key = e.Key, Value = e.Value, Hash = e.Hash }; - this.AddToBuckets(nextBucket, key, newEntry, null, out resultingValue); - e = e.Next; - } - } - - // add entry(if failed to add, only do resize) - var successAdd = this.AddToBuckets(nextBucket, key, null, valueFactory, out resultingValue); - - // replace field(threadsafe for read) - VolatileWrite(ref this.buckets, nextBucket); - - if (successAdd) - { - this.size++; - } - - return successAdd; - } - else - { - // add entry(insert last is thread safe for read) - var successAdd = this.AddToBuckets(this.buckets, key, null, valueFactory, out resultingValue); - if (successAdd) - { - this.size++; - } - - return successAdd; - } - } - } - - private bool AddToBuckets(Entry[] buckets, TKey1 newKey, Entry newEntryOrNull, Func valueFactory, out TValue resultingValue) - { - var h = (newEntryOrNull != null) ? newEntryOrNull.Hash : this.comparer.GetHashCode(newKey); - if (buckets[h & (buckets.Length - 1)] == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref buckets[h & (buckets.Length - 1)], newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref buckets[h & (buckets.Length - 1)], new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - } - else - { - Entry searchLastEntry = buckets[h & (buckets.Length - 1)]; - while (true) - { - if (this.comparer.Equals(searchLastEntry.Key, newKey)) - { - resultingValue = searchLastEntry.Value; - return false; - } - - if (searchLastEntry.Next == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref searchLastEntry.Next, newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref searchLastEntry.Next, new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - - break; - } - - searchLastEntry = searchLastEntry.Next; - } - } - - return true; - } - - public bool TryGetValue(TKey2 key, out TValue value) - { - Entry[] table = this.buckets; - var hash = this.comparer.GetHashCode(key); - Entry entry = table[hash & table.Length - 1]; - - if (entry == null) - { - goto NOT_FOUND; - } - - if (this.comparer.Equals(entry.Key, key)) - { - value = entry.Value; - return true; - } - - Entry next = entry.Next; - while (next != null) - { - if (this.comparer.Equals(next.Key, key)) - { - value = next.Value; - return true; - } - - next = next.Next; - } - -NOT_FOUND: - value = default(TValue); - return false; - } - - private static int CalculateCapacity(int collectionSize, float loadFactor) - { - var initialCapacity = (int)(((float)collectionSize) / loadFactor); - var capacity = 1; - while (capacity < initialCapacity) - { - capacity <<= 1; - } - - if (capacity < 8) - { - return 8; - } - - return capacity; - } - - private static void VolatileWrite(ref Entry location, Entry value) - { - System.Threading.Volatile.Write(ref location, value); - } - - private static void VolatileWrite(ref Entry[] location, Entry[] value) - { - System.Threading.Volatile.Write(ref location, value); - } - - private class Entry - { -#pragma warning disable SA1401 // Fields should be private - internal TKey1 Key; - internal TValue Value; - internal int Hash; - internal Entry Next; -#pragma warning restore SA1401 // Fields should be private - - // from debugger only - public override string ToString() - { - return "Count:" + this.Count; - } - - internal int Count - { - get - { - var count = 1; - Entry n = this; - while (n.Next != null) - { - count++; - n = n.Next; - } - - return count; - } - } - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AsymmetricKeyHashTable.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AsymmetricKeyHashTable.cs.meta deleted file mode 100644 index 2aec9f2..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AsymmetricKeyHashTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fe3bf5c42bc27c1429b9e8bd1839b8e0 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AutomataDictionary.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AutomataDictionary.cs deleted file mode 100644 index 11e017a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AutomataDictionary.cs +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.InteropServices; -using System.Text; - -#pragma warning disable SA1509 // Opening braces should not be preceded by blank line - -namespace MessagePack.Internal -{ - // Key = long, Value = int for UTF8String Dictionary - - /// - /// This code is used by dynamically generated code as well as AOT generated code, - /// and thus must be public for the "C# generated and compiled into saved assembly" scenario. - /// - public class AutomataDictionary : IEnumerable> - { - private readonly AutomataNode root; - - public AutomataDictionary() - { - this.root = new AutomataNode(0); - } - - public void Add(string str, int value) - { - ReadOnlySpan bytes = Encoding.UTF8.GetBytes(str); - AutomataNode node = this.root; - - while (bytes.Length > 0) - { - var key = AutomataKeyGen.GetKey(ref bytes); - - if (bytes.Length == 0) - { - node = node.Add(key, value, str); - } - else - { - node = node.Add(key); - } - } - } - - public bool TryGetValue(in ReadOnlySequence bytes, out int value) => this.TryGetValue(bytes.ToArray(), out value); - - public bool TryGetValue(ReadOnlySpan bytes, out int value) - { - AutomataNode node = this.root; - - while (bytes.Length > 0 && node != null) - { - node = node.SearchNext(ref bytes); - } - - if (node == null) - { - value = -1; - return false; - } - else - { - value = node.Value; - return true; - } - } - - // for debugging - public override string ToString() - { - var sb = new StringBuilder(); - ToStringCore(this.root.YieldChildren(), sb, 0); - return sb.ToString(); - } - - private static void ToStringCore(IEnumerable nexts, StringBuilder sb, int depth) - { - foreach (AutomataNode item in nexts) - { - if (depth != 0) - { - sb.Append(' ', depth * 2); - } - - sb.Append("[" + item.Key + "]"); - if (item.Value != -1) - { - sb.Append("(" + item.OriginalKey + ")"); - sb.Append(" = "); - sb.Append(item.Value); - } - - sb.AppendLine(); - ToStringCore(item.YieldChildren(), sb, depth + 1); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.GetEnumerator(); - } - - public IEnumerator> GetEnumerator() - { - return YieldCore(this.root.YieldChildren()).GetEnumerator(); - } - - private static IEnumerable> YieldCore(IEnumerable nexts) - { - foreach (AutomataNode item in nexts) - { - if (item.Value != -1) - { - yield return new KeyValuePair(item.OriginalKey, item.Value); - } - - foreach (KeyValuePair x in YieldCore(item.YieldChildren())) - { - yield return x; - } - } - } - - /* IL Emit */ - -#if !NET_STANDARD_2_0 - - public void EmitMatch(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action> onFound, Action onNotFound) - { - this.root.EmitSearchNext(il, bytesSpan, key, onFound, onNotFound); - } - -#endif - - private class AutomataNode : IComparable - { -#pragma warning disable SA1401 // Fields should be private - internal ulong Key; - internal int Value; - internal string OriginalKey; -#pragma warning restore SA1401 // Fields should be private - - private AutomataNode[] nexts; - private ulong[] nextKeys; - private int count; - - public bool HasChildren - { - get { return this.count != 0; } - } - - public AutomataNode(ulong key) - { - this.Key = key; - this.Value = -1; - this.nexts = Array.Empty(); - this.nextKeys = Array.Empty(); - this.count = 0; - this.OriginalKey = null; - } - - public AutomataNode Add(ulong key) - { - var index = Array.BinarySearch(this.nextKeys, 0, this.count, key); - if (index < 0) - { - if (this.nexts.Length == this.count) - { - Array.Resize(ref this.nexts, (this.count == 0) ? 4 : (this.count * 2)); - Array.Resize(ref this.nextKeys, (this.count == 0) ? 4 : (this.count * 2)); - } - - this.count++; - - var nextNode = new AutomataNode(key); - this.nexts[this.count - 1] = nextNode; - this.nextKeys[this.count - 1] = key; - Array.Sort(this.nexts, 0, this.count); - Array.Sort(this.nextKeys, 0, this.count); - return nextNode; - } - else - { - return this.nexts[index]; - } - } - - public AutomataNode Add(ulong key, int value, string originalKey) - { - AutomataNode v = this.Add(key); - v.Value = value; - v.OriginalKey = originalKey; - return v; - } - - public AutomataNode SearchNext(ref ReadOnlySpan value) - { - var key = AutomataKeyGen.GetKey(ref value); - if (this.count < 4) - { - // linear search - for (int i = 0; i < this.count; i++) - { - if (this.nextKeys[i] == key) - { - return this.nexts[i]; - } - } - } - else - { - // binary search - var index = BinarySearch(this.nextKeys, 0, this.count, key); - if (index >= 0) - { - return this.nexts[index]; - } - } - - return null; - } - - internal static int BinarySearch(ulong[] array, int index, int length, ulong value) - { - int lo = index; - int hi = index + length - 1; - while (lo <= hi) - { - int i = lo + ((hi - lo) >> 1); - - var arrayValue = array[i]; - int order; - if (arrayValue < value) - { - order = -1; - } - else if (arrayValue > value) - { - order = 1; - } - else - { - order = 0; - } - - if (order == 0) - { - return i; - } - - if (order < 0) - { - lo = i + 1; - } - else - { - hi = i - 1; - } - } - - return ~lo; - } - - public int CompareTo(AutomataNode other) - { - return this.Key.CompareTo(other.Key); - } - - public IEnumerable YieldChildren() - { - for (int i = 0; i < this.count; i++) - { - yield return this.nexts[i]; - } - } - -#if !NET_STANDARD_2_0 - - // SearchNext(ref ReadOnlySpan bytes) - public void EmitSearchNext(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action> onFound, Action onNotFound) - { - // key = AutomataKeyGen.GetKey(ref bytesSpan); - il.EmitLdloca(bytesSpan); - il.EmitCall(AutomataKeyGen.GetKeyMethod); - il.EmitStloc(key); - - // match children. - EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, this.nexts, this.count); - } - - private static void EmitSearchNextCore(ILGenerator il, LocalBuilder bytesSpan, LocalBuilder key, Action> onFound, Action onNotFound, AutomataNode[] nexts, int count) - { - if (count < 4) - { - // linear-search - AutomataNode[] valueExists = nexts.Take(count).Where(x => x.Value != -1).ToArray(); - AutomataNode[] childrenExists = nexts.Take(count).Where(x => x.HasChildren).ToArray(); - Label gotoSearchNext = il.DefineLabel(); - Label gotoNotFound = il.DefineLabel(); - - { - // bytesSpan.Length - il.EmitLdloca(bytesSpan); - il.EmitCall(typeof(ReadOnlySpan).GetRuntimeProperty(nameof(ReadOnlySpan.Length)).GetMethod); - if (childrenExists.Length != 0 && valueExists.Length == 0) - { - il.Emit(OpCodes.Brfalse, gotoNotFound); // if(bytesSpan.Length == 0) - } - else - { - il.Emit(OpCodes.Brtrue, gotoSearchNext); // if(bytesSpan.Length != 0) - } - } - - { - Label[] ifValueNexts = Enumerable.Range(0, Math.Max(valueExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray(); - for (int i = 0; i < valueExists.Length; i++) - { - Label notFoundLabel = il.DefineLabel(); - if (i != 0) - { - il.MarkLabel(ifValueNexts[i - 1]); - } - - il.EmitLdloc(key); - il.EmitULong(valueExists[i].Key); - il.Emit(OpCodes.Bne_Un, notFoundLabel); - - // found - onFound(new KeyValuePair(valueExists[i].OriginalKey, valueExists[i].Value)); - - // notfound - il.MarkLabel(notFoundLabel); - if (i != valueExists.Length - 1) - { - il.Emit(OpCodes.Br, ifValueNexts[i]); - } - else - { - onNotFound(); - } - } - } - - il.MarkLabel(gotoSearchNext); - Label[] ifRecNext = Enumerable.Range(0, Math.Max(childrenExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray(); - for (int i = 0; i < childrenExists.Length; i++) - { - Label notFoundLabel = il.DefineLabel(); - if (i != 0) - { - il.MarkLabel(ifRecNext[i - 1]); - } - - il.EmitLdloc(key); - il.EmitULong(childrenExists[i].Key); - il.Emit(OpCodes.Bne_Un, notFoundLabel); - - // found - childrenExists[i].EmitSearchNext(il, bytesSpan, key, onFound, onNotFound); - - // notfound - il.MarkLabel(notFoundLabel); - if (i != childrenExists.Length - 1) - { - il.Emit(OpCodes.Br, ifRecNext[i]); - } - else - { - onNotFound(); - } - } - - il.MarkLabel(gotoNotFound); - onNotFound(); - } - else - { - // binary-search - var midline = count / 2; - var mid = nexts[midline].Key; - AutomataNode[] l = nexts.Take(count).Take(midline).ToArray(); - AutomataNode[] r = nexts.Take(count).Skip(midline).ToArray(); - - Label gotoRight = il.DefineLabel(); - - // if(key < mid) - il.EmitLdloc(key); - il.EmitULong(mid); - il.Emit(OpCodes.Bge_Un, gotoRight); - EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, l, l.Length); - - // else - il.MarkLabel(gotoRight); - EmitSearchNextCore(il, bytesSpan, key, onFound, onNotFound, r, r.Length); - } - } - -#endif - } - } - - /// - /// This is used by dynamically generated code. It can be made internal after we enable our dynamic assemblies to access internals. - /// But that trick may require net46, so maybe we should leave this as public. - /// - public static class AutomataKeyGen - { - public static readonly MethodInfo GetKeyMethod = typeof(AutomataKeyGen).GetRuntimeMethod(nameof(GetKey), new[] { typeof(ReadOnlySpan).MakeByRefType() }); - - public static ulong GetKey(ref ReadOnlySpan span) - { - ulong key; - - unchecked - { - if (span.Length >= 8) - { - key = SafeBitConverter.ToUInt64(span); - span = span.Slice(8); - } - else - { - switch (span.Length) - { - case 1: - { - key = span[0]; - span = span.Slice(1); - break; - } - - case 2: - { - key = SafeBitConverter.ToUInt16(span); - span = span.Slice(2); - break; - } - - case 3: - { - var a = span[0]; - var b = SafeBitConverter.ToUInt16(span.Slice(1)); - key = a | (ulong)b << 8; - span = span.Slice(3); - break; - } - - case 4: - { - key = SafeBitConverter.ToUInt32(span); - span = span.Slice(4); - break; - } - - case 5: - { - var a = span[0]; - var b = SafeBitConverter.ToUInt32(span.Slice(1)); - key = a | (ulong)b << 8; - span = span.Slice(5); - break; - } - - case 6: - { - ulong a = SafeBitConverter.ToUInt16(span); - ulong b = SafeBitConverter.ToUInt32(span.Slice(2)); - key = a | (b << 16); - span = span.Slice(6); - break; - } - - case 7: - { - var a = span[0]; - var b = SafeBitConverter.ToUInt16(span.Slice(1)); - var c = SafeBitConverter.ToUInt32(span.Slice(3)); - key = a | (ulong)b << 8 | (ulong)c << 24; - span = span.Slice(7); - break; - } - - default: - throw new MessagePackSerializationException("Not Supported Length"); - } - } - - return key; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AutomataDictionary.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AutomataDictionary.cs.meta deleted file mode 100644 index c9c57e7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/AutomataDictionary.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 14776842f04657842b044268a62cf6b2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ByteArrayStringHashTable.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ByteArrayStringHashTable.cs deleted file mode 100644 index dc1d4d4..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ByteArrayStringHashTable.cs +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Text; - -namespace MessagePack.Internal -{ - // like ArraySegment hashtable. - // Add is safe for construction phase only and requires capacity(does not do rehash) - // and specialized for internal use(nongenerics, TValue is int) - - // internal, but code generator requires this class - // or at least PerfBenchmarkDotNet - public class ByteArrayStringHashTable : IEnumerable> - { - private readonly Entry[][] buckets; // immutable array(faster than linkedlist) - private readonly ulong indexFor; - - public ByteArrayStringHashTable(int capacity) - : this(capacity, 0.42f) // default: 0.75f -> 0.42f - { - } - - public ByteArrayStringHashTable(int capacity, float loadFactor) - { - var tableSize = CalculateCapacity(capacity, loadFactor); - this.buckets = new Entry[tableSize][]; - this.indexFor = (ulong)this.buckets.Length - 1; - } - - public void Add(string key, int value) - { - if (!this.TryAddInternal(Encoding.UTF8.GetBytes(key), value)) - { - throw new ArgumentException("Key was already exists. Key:" + key); - } - } - - public void Add(byte[] key, int value) - { - if (!this.TryAddInternal(key, value)) - { - throw new ArgumentException("Key was already exists. Key:" + key); - } - } - - private bool TryAddInternal(byte[] key, int value) - { - var h = ByteArrayGetHashCode(key); - var entry = new Entry { Key = key, Value = value }; - - Entry[] array = this.buckets[h & this.indexFor]; - if (array == null) - { - this.buckets[h & this.indexFor] = new[] { entry }; - } - else - { - // check duplicate - for (int i = 0; i < array.Length; i++) - { - byte[] e = array[i].Key; - if (key.AsSpan().SequenceEqual(e)) - { - return false; - } - } - - var newArray = new Entry[array.Length + 1]; - Array.Copy(array, newArray, array.Length); - array = newArray; - array[array.Length - 1] = entry; - this.buckets[h & this.indexFor] = array; - } - - return true; - } - - public bool TryGetValue(in ReadOnlySequence key, out int value) => this.TryGetValue(CodeGenHelpers.GetSpanFromSequence(key), out value); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryGetValue(ReadOnlySpan key, out int value) - { - Entry[][] table = this.buckets; - var hash = ByteArrayGetHashCode(key); - Entry[] entry = table[hash & this.indexFor]; - - if (entry == null) - { - value = default(int); - return false; - } - - ref Entry v = ref entry[0]; - if (key.SequenceEqual(v.Key)) - { - value = v.Value; - return true; - } - - return TryGetValueSlow(key, entry, out value); - } - - private bool TryGetValueSlow(ReadOnlySpan key, Entry[] entry, out int value) - { - for (int i = 1; i < entry.Length; i++) - { - ref Entry v = ref entry[i]; - if (key.SequenceEqual(v.Key)) - { - value = v.Value; - return true; - } - } - - value = default(int); - return false; - } - - private static readonly bool Is32Bit = IntPtr.Size == 4; - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - private static ulong ByteArrayGetHashCode(ReadOnlySpan x) - { - // FarmHash https://github.com/google/farmhash - if (Is32Bit) - { - return (ulong)FarmHash.Hash32(x); - } - else - { - return FarmHash.Hash64(x); - } - } - - private static int CalculateCapacity(int collectionSize, float loadFactor) - { - var initialCapacity = (int)(((float)collectionSize) / loadFactor); - var capacity = 1; - while (capacity < initialCapacity) - { - capacity <<= 1; - } - - if (capacity < 8) - { - return 8; - } - - return capacity; - } - - // only for Debug use - public IEnumerator> GetEnumerator() - { - Entry[][] b = this.buckets; - - foreach (Entry[] item in b) - { - if (item == null) - { - continue; - } - - foreach (Entry item2 in item) - { - yield return new KeyValuePair(Encoding.UTF8.GetString(item2.Key), item2.Value); - } - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.GetEnumerator(); - } - - private struct Entry - { - public byte[] Key; - public int Value; - - // for debugging - public override string ToString() - { - return "(" + Encoding.UTF8.GetString(this.Key) + ", " + this.Value + ")"; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ByteArrayStringHashTable.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ByteArrayStringHashTable.cs.meta deleted file mode 100644 index 411760a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ByteArrayStringHashTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4df68ce4d7981d244b9a6e7991ef717d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/CodeGenHelpers.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/CodeGenHelpers.cs deleted file mode 100644 index b08a5ac..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/CodeGenHelpers.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.ComponentModel; - -namespace MessagePack.Internal -{ - /// - /// Helpers for generated code. - /// - /// - /// This code is used by dynamically generated code as well as AOT generated code, - /// and thus must be public for the "C# generated and compiled into saved assembly" scenario. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public static class CodeGenHelpers - { - /// - /// Gets the messagepack encoding for a given string. - /// - /// The string to encode. - /// The messagepack encoding for , including messagepack header and UTF-8 bytes. - public static byte[] GetEncodedStringBytes(string value) - { - var byteCount = StringEncoding.UTF8.GetByteCount(value); - if (byteCount <= MessagePackRange.MaxFixStringLength) - { - var bytes = new byte[byteCount + 1]; - bytes[0] = (byte)(MessagePackCode.MinFixStr | byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 1); - return bytes; - } - else if (byteCount <= byte.MaxValue) - { - var bytes = new byte[byteCount + 2]; - bytes[0] = MessagePackCode.Str8; - bytes[1] = unchecked((byte)byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 2); - return bytes; - } - else if (byteCount <= ushort.MaxValue) - { - var bytes = new byte[byteCount + 3]; - bytes[0] = MessagePackCode.Str16; - bytes[1] = unchecked((byte)(byteCount >> 8)); - bytes[2] = unchecked((byte)byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 3); - return bytes; - } - else - { - var bytes = new byte[byteCount + 5]; - bytes[0] = MessagePackCode.Str32; - bytes[1] = unchecked((byte)(byteCount >> 24)); - bytes[2] = unchecked((byte)(byteCount >> 16)); - bytes[3] = unchecked((byte)(byteCount >> 8)); - bytes[4] = unchecked((byte)byteCount); - StringEncoding.UTF8.GetBytes(value, 0, value.Length, bytes, 5); - return bytes; - } - } - - /// - /// Gets a single containing all bytes in a given . - /// An array may be allocated if the bytes are not already contiguous in memory. - /// - /// The sequence to get a span for. - /// The span. - public static ReadOnlySpan GetSpanFromSequence(in ReadOnlySequence sequence) - { - if (sequence.IsSingleSegment) - { - return sequence.First.Span; - } - - return sequence.ToArray(); - } - - /// - /// Reads a string as a contiguous span of UTF-8 encoded characters. - /// An array may be allocated if the string is not already contiguous in memory. - /// - /// The reader to use. - /// The span of UTF-8 encoded characters. - public static ReadOnlySpan ReadStringSpan(ref MessagePackReader reader) - { - if (!reader.TryReadStringSpan(out ReadOnlySpan result)) - { - return GetSpanFromSequence(reader.ReadStringSequence()); - } - - return result; - } - - /// - /// Creates a array for a given sequence, or if the optional sequence is itself . - /// - /// The sequence. - /// The byte array or . - public static byte[] GetArrayFromNullableSequence(in ReadOnlySequence? sequence) => sequence?.ToArray(); - - private static ReadOnlySpan GetSpanFromSequence(in ReadOnlySequence? sequence) - { - return sequence.HasValue ? GetSpanFromSequence(sequence.Value) : default; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/CodeGenHelpers.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/CodeGenHelpers.cs.meta deleted file mode 100644 index 5191b26..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/CodeGenHelpers.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e733605ab88010a4686b39fea27fe38b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DateTimeConstants.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DateTimeConstants.cs deleted file mode 100644 index 84fbfe9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DateTimeConstants.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack.Internal -{ - internal static class DateTimeConstants - { - internal const long BclSecondsAtUnixEpoch = 62135596800; - internal const int NanosecondsPerTick = 100; - internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DateTimeConstants.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DateTimeConstants.cs.meta deleted file mode 100644 index 267c348..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DateTimeConstants.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4b25d1986c9838643ac125bc06eac98c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DynamicAssembly.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DynamicAssembly.cs deleted file mode 100644 index f5988af..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DynamicAssembly.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Reflection; -using System.Reflection.Emit; - -namespace MessagePack.Internal -{ - internal class DynamicAssembly - { -#if NETFRAMEWORK // We don't ship a net472 target, but we might add one for debugging purposes - private readonly string moduleName; -#endif - private readonly AssemblyBuilder assemblyBuilder; - private readonly ModuleBuilder moduleBuilder; - - // don't expose ModuleBuilder - //// public ModuleBuilder ModuleBuilder { get { return moduleBuilder; } } - - public DynamicAssembly(string moduleName) - { -#if NETFRAMEWORK // We don't ship a net472 target, but we might add one for debugging purposes - AssemblyBuilderAccess builderAccess = AssemblyBuilderAccess.RunAndSave; - this.moduleName = moduleName; -#else - AssemblyBuilderAccess builderAccess = AssemblyBuilderAccess.Run; -#endif - this.assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(moduleName), builderAccess); - this.moduleBuilder = this.assemblyBuilder.DefineDynamicModule(moduleName + ".dll"); - } - - /* requires lock on mono environment. see: https://github.com/neuecc/MessagePack-CSharp/issues/161 */ - - public TypeBuilder DefineType(string name, TypeAttributes attr) => this.moduleBuilder.DefineType(name, attr); - - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent) => this.moduleBuilder.DefineType(name, attr, parent); - - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, Type[] interfaces) => this.moduleBuilder.DefineType(name, attr, parent, interfaces); - -#if NETFRAMEWORK - - public AssemblyBuilder Save() - { - this.assemblyBuilder.Save(this.moduleName + ".dll"); - return this.assemblyBuilder; - } - -#endif - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DynamicAssembly.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DynamicAssembly.cs.meta deleted file mode 100644 index 21023e7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/DynamicAssembly.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9c3c62d8dc2404b43b89833c076e73ef -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ExpressionUtility.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ExpressionUtility.cs deleted file mode 100644 index 3dbf46e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ExpressionUtility.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq.Expressions; -using System.Reflection; - -namespace MessagePack.Internal -{ - internal static class ExpressionUtility - { - private static MethodInfo GetMethodInfoCore(LambdaExpression expression) - { - if (expression == null) - { - throw new ArgumentNullException("expression"); - } - - return (expression.Body as MethodCallExpression).Method; - } - - /// - /// Get MethodInfo from Expression for Static(with result) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - /// - /// Get MethodInfo from Expression for Static(void) method. - /// - public static MethodInfo GetMethodInfo(Expression expression) - { - return GetMethodInfoCore(expression); - } - - /// - /// Get MethodInfo from Expression for Instance(with result) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - /// - /// Get MethodInfo from Expression for Instance(void) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - // WithArgument(for ref, out) helper - - /// - /// Get MethodInfo from Expression for Instance(with result) method. - /// - public static MethodInfo GetMethodInfo(Expression> expression) - { - return GetMethodInfoCore(expression); - } - - private static MemberInfo GetMemberInfoCore(Expression source) - { - if (source == null) - { - throw new ArgumentNullException("source"); - } - - var memberExpression = source.Body as MemberExpression; - return memberExpression.Member; - } - - public static PropertyInfo GetPropertyInfo(Expression> expression) - { - return GetMemberInfoCore(expression) as PropertyInfo; - } - - public static FieldInfo GetFieldInfo(Expression> expression) - { - return GetMemberInfoCore(expression) as FieldInfo; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ExpressionUtility.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ExpressionUtility.cs.meta deleted file mode 100644 index 4cf4794..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ExpressionUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 79cc2e793fd7f1047b6c6e9718b59912 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/FarmHash.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/FarmHash.cs deleted file mode 100644 index 36d4b8e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/FarmHash.cs +++ /dev/null @@ -1,601 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.CompilerServices; - -#pragma warning disable SA1300 // Element should begin with uppercase letter -#pragma warning disable SA1303 // Const field names should begin with uppercase letter -#pragma warning disable SA1307 // (public) field names should begin with uppercase letter - -namespace MessagePack.Internal -{ - internal static class FarmHash - { - #region Hash32 - - // entry point of 32bit - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe uint Hash32(ReadOnlySpan bytes) - { - if (bytes.Length <= 4) - { - return Hash32Len0to4(bytes); - } - - fixed (byte* p = bytes) - { - return Hash32(p, (uint)bytes.Length); - } - } - - // port of farmhash.cc, 32bit only - - // Magic numbers for 32-bit hashing. Copied from Murmur3. - private const uint c1 = 0xcc9e2d51; - private const uint c2 = 0x1b873593; - - private static unsafe uint Fetch32(byte* p) - { - return *(uint*)p; - } - - private static uint Rotate32(uint val, int shift) - { - return shift == 0 ? val : ((val >> shift) | (val << (32 - shift))); - } - - // A 32-bit to 32-bit integer hash copied from Murmur3. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint fmix(uint h) - { - unchecked - { - h ^= h >> 16; - h *= 0x85ebca6b; - h ^= h >> 13; - h *= 0xc2b2ae35; - h ^= h >> 16; - return h; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint Mur(uint a, uint h) - { - unchecked - { - // Helper from Murmur3 for combining two 32-bit values. - a *= c1; - a = Rotate32(a, 17); - a *= c2; - h ^= a; - h = Rotate32(h, 19); - return (h * 5) + 0xe6546b64; - } - } - - // 0-4 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32Len0to4(ReadOnlySpan s) - { - unchecked - { - uint b = 0; - uint c = 9; - for (int i = 0; i < s.Length; i++) - { - b = (b * c1) + s[i]; - c ^= b; - } - - return fmix(Mur(b, Mur((uint)s.Length, c))); - } - } - - // 5-12 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32Len5to12(byte* s, uint len) - { - unchecked - { - uint a = len, b = len * 5, c = 9, d = b; - a += Fetch32(s); - b += Fetch32(s + len - 4); - c += Fetch32(s + ((len >> 1) & 4)); - return fmix(Mur(c, Mur(b, Mur(a, d)))); - } - } - - // 13-24 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32Len13to24(byte* s, uint len) - { - unchecked - { - uint a = Fetch32(s - 4 + (len >> 1)); - uint b = Fetch32(s + 4); - uint c = Fetch32(s + len - 8); - uint d = Fetch32(s + (len >> 1)); - uint e = Fetch32(s); - uint f = Fetch32(s + len - 4); - uint h = (d * c1) + len; - a = Rotate32(a, 12) + f; - h = Mur(c, h) + a; - a = Rotate32(a, 3) + c; - h = Mur(e, h) + a; - a = Rotate32(a + f, 12) + d; - h = Mur(b, h) + a; - return fmix(h); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe uint Hash32(byte* s, uint len) - { - if (len <= 24) - { - return len <= 12 ? Hash32Len5to12(s, len) : Hash32Len13to24(s, len); - } - - unchecked - { - // len > 24 - uint h = len, g = c1 * len, f = g; - uint a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2; - uint a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2; - uint a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2; - uint a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2; - uint a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2; - h ^= a0; - h = Rotate32(h, 19); - h = (h * 5) + 0xe6546b64; - h ^= a2; - h = Rotate32(h, 19); - h = (h * 5) + 0xe6546b64; - g ^= a1; - g = Rotate32(g, 19); - g = (g * 5) + 0xe6546b64; - g ^= a3; - g = Rotate32(g, 19); - g = (g * 5) + 0xe6546b64; - f += a4; - f = Rotate32(f, 19) + 113; - uint iters = (len - 1) / 20; - do - { - uint a = Fetch32(s); - uint b = Fetch32(s + 4); - uint c = Fetch32(s + 8); - uint d = Fetch32(s + 12); - uint e = Fetch32(s + 16); - h += a; - g += b; - f += c; - h = Mur(d, h) + e; - g = Mur(c, g) + a; - f = Mur(b + (e * c1), f) + d; - f += g; - g += f; - s += 20; - } - while (--iters != 0); - g = Rotate32(g, 11) * c1; - g = Rotate32(g, 17) * c1; - f = Rotate32(f, 11) * c1; - f = Rotate32(f, 17) * c1; - h = Rotate32(h + g, 19); - h = (h * 5) + 0xe6546b64; - h = Rotate32(h, 17) * c1; - h = Rotate32(h + f, 19); - h = (h * 5) + 0xe6546b64; - h = Rotate32(h, 17) * c1; - return h; - } - } - - #endregion - - #region hash64 - - // entry point - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ulong Hash64(ReadOnlySpan bytes) - { - fixed (byte* p = bytes) - { - return Hash64(p, (uint)bytes.Length); - } - } - - /* port from farmhash.cc */ - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void swap(ref ulong x, ref ulong z) - { - var temp = z; - z = x; - x = temp; - } - - // Some primes between 2^63 and 2^64 for various uses. - private const ulong k0 = 0xc3a5c85c97cb3127UL; - private const ulong k1 = 0xb492b66fbe98f273UL; - private const ulong k2 = 0x9ae16a3b2f90404fUL; - - private static unsafe ulong Fetch64(byte* p) - { - return *(ulong*)p; - } - - private static ulong Rotate64(ulong val, int shift) - { - return shift == 0 ? val : (val >> shift) | (val << (64 - shift)); - } - - // farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ulong ShiftMix(ulong val) - { - return val ^ (val >> 47); - } - - // farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ulong HashLen16(ulong u, ulong v, ulong mul) - { - unchecked - { - // Murmur-inspired hashing. - ulong a = (u ^ v) * mul; - a ^= a >> 47; - ulong b = (v ^ a) * mul; - b ^= b >> 47; - b *= mul; - return b; - } - } - - // farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong Hash64(byte* s, uint len) - { - if (len <= 16) - { - // farmhashna:: - return HashLen0to16(s, len); - } - - if (len <= 32) - { - // farmhashna:: - return HashLen17to32(s, len); - } - - if (len <= 64) - { - return HashLen33to64(s, len); - } - - if (len <= 96) - { - return HashLen65to96(s, len); - } - - if (len <= 256) - { - // farmhashna:: - return Hash64NA(s, len); - } - - // farmhashuo:: - return Hash64UO(s, len); - } - - // 0-16 farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen0to16(byte* s, uint len) - { - unchecked - { - if (len >= 8) - { - ulong mul = k2 + (len * 2); - ulong a = Fetch64(s) + k2; - ulong b = Fetch64(s + len - 8); - ulong c = (Rotate64(b, 37) * mul) + a; - ulong d = (Rotate64(a, 25) + b) * mul; - return HashLen16(c, d, mul); - } - - if (len >= 4) - { - ulong mul = k2 + (len * 2); - ulong a = Fetch32(s); - return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul); - } - - if (len > 0) - { - ushort a = s[0]; - ushort b = s[len >> 1]; - ushort c = s[len - 1]; - uint y = a + ((uint)b << 8); - uint z = len + ((uint)c << 2); - return ShiftMix(y * k2 ^ z * k0) * k2; - } - - return k2; - } - } - - // 17-32 farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen17to32(byte* s, uint len) - { - unchecked - { - ulong mul = k2 + (len * 2); - ulong a = Fetch64(s) * k1; - ulong b = Fetch64(s + 8); - ulong c = Fetch64(s + len - 8) * mul; - ulong d = Fetch64(s + len - 16) * k2; - return HashLen16( - Rotate64(a + b, 43) + Rotate64(c, 30) + d, - a + Rotate64(b + k2, 18) + c, - mul); - } - } - - // farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong H32(byte* s, uint len, ulong mul, ulong seed0 = 0, ulong seed1 = 0) - { - unchecked - { - ulong a = Fetch64(s) * k1; - ulong b = Fetch64(s + 8); - ulong c = Fetch64(s + len - 8) * mul; - ulong d = Fetch64(s + len - 16) * k2; - ulong u = Rotate64(a + b, 43) + Rotate64(c, 30) + d + seed0; - ulong v = a + Rotate64(b + k2, 18) + c + seed1; - a = ShiftMix((u ^ v) * mul); - b = ShiftMix((v ^ a) * mul); - return b; - } - } - - // 33-64 farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen33to64(byte* s, uint len) - { - const ulong mul0 = k2 - 30; - - unchecked - { - ulong mul1 = k2 - 30 + (2 * len); - ulong h0 = H32(s, 32, mul0); - ulong h1 = H32(s + len - 32, 32, mul1); - return ((h1 * mul1) + h0) * mul1; - } - } - - // 65-96 farmhashxo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong HashLen65to96(byte* s, uint len) - { - const ulong mul0 = k2 - 114; - - unchecked - { - ulong mul1 = k2 - 114 + (2 * len); - ulong h0 = H32(s, 32, mul0); - ulong h1 = H32(s + 32, 32, mul1); - ulong h2 = H32(s + len - 32, 32, mul1, h0, h1); - return ((h2 * 9) + (h0 >> 17) + (h1 >> 21)) * mul1; - } - } - - // farmhashna.cc - // Return a 16-byte hash for 48 bytes. Quick and dirty. - // Callers do best to use "random-looking" values for a and b. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe void WeakHashLen32WithSeeds(ulong w, ulong x, ulong y, ulong z, ulong a, ulong b, out ulong first, out ulong second) - { - unchecked - { - a += w; - b = Rotate64(b + a + z, 21); - ulong c = a; - a += x; - a += y; - b += Rotate64(a, 44); - first = a + z; - second = b + c; - } - } - - // farmhashna.cc - // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe void WeakHashLen32WithSeeds(byte* s, ulong a, ulong b, out ulong first, out ulong second) - { - WeakHashLen32WithSeeds( - Fetch64(s), - Fetch64(s + 8), - Fetch64(s + 16), - Fetch64(s + 24), - a, - b, - out first, - out second); - } - - // na(97-256) farmhashna.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong Hash64NA(byte* s, uint len) - { - const ulong seed = 81; - - unchecked - { - // For strings over 64 bytes we loop. Internal state consists of - // 56 bytes: v, w, x, y, and z. - ulong x = seed; - ulong y = (seed * k1) + 113; - ulong z = ShiftMix((y * k2) + 113) * k2; - ulong v_first = 0; - ulong v_second = 0; - ulong w_first = 0; - ulong w_second = 0; - x = (x * k2) + Fetch64(s); - - // Set end so that after the loop we have 1 to 64 bytes left to process. - byte* end = s + ((len - 1) / 64 * 64); - byte* last64 = end + ((len - 1) & 63) - 63; - - do - { - x = Rotate64(x + y + v_first + Fetch64(s + 8), 37) * k1; - y = Rotate64(y + v_second + Fetch64(s + 48), 42) * k1; - x ^= w_second; - y += v_first + Fetch64(s + 40); - z = Rotate64(z + w_first, 33) * k1; - WeakHashLen32WithSeeds(s, v_second * k1, x + w_first, out v_first, out v_second); - WeakHashLen32WithSeeds(s + 32, z + w_second, y + Fetch64(s + 16), out w_first, out w_second); - swap(ref z, ref x); - s += 64; - } - while (s != end); - ulong mul = k1 + ((z & 0xff) << 1); - - // Make s point to the last 64 bytes of input. - s = last64; - w_first += (len - 1) & 63; - v_first += w_first; - w_first += v_first; - x = Rotate64(x + y + v_first + Fetch64(s + 8), 37) * mul; - y = Rotate64(y + v_second + Fetch64(s + 48), 42) * mul; - x ^= w_second * 9; - y += (v_first * 9) + Fetch64(s + 40); - z = Rotate64(z + w_first, 33) * mul; - WeakHashLen32WithSeeds(s, v_second * mul, x + w_first, out v_first, out v_second); - WeakHashLen32WithSeeds(s + 32, z + w_second, y + Fetch64(s + 16), out w_first, out w_second); - swap(ref z, ref x); - return HashLen16(HashLen16(v_first, w_first, mul) + (ShiftMix(y) * k0) + z, HashLen16(v_second, w_second, mul) + x, mul); - } - } - - // farmhashuo.cc - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static ulong H(ulong x, ulong y, ulong mul, int r) - { - unchecked - { - ulong a = (x ^ y) * mul; - a ^= a >> 47; - ulong b = (y ^ a) * mul; - return Rotate64(b, r) * mul; - } - } - - // uo(257-) farmhashuo.cc, Hash64WithSeeds - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe ulong Hash64UO(byte* s, uint len) - { - const ulong seed0 = 81; - const ulong seed1 = 0; - - unchecked - { - // For strings over 64 bytes we loop. Internal state consists of - // 64 bytes: u, v, w, x, y, and z. - ulong x = seed0; - ulong y = (seed1 * k2) + 113; - ulong z = ShiftMix(y * k2) * k2; - ulong v_first = seed0; - ulong v_second = seed1; - ulong w_first = 0; - ulong w_second = 0; - ulong u = x - z; - x *= k2; - ulong mul = k2 + (u & 0x82); - - // Set end so that after the loop we have 1 to 64 bytes left to process. - byte* end = s + ((len - 1) / 64 * 64); - byte* last64 = end + ((len - 1) & 63) - 63; - - do - { - ulong a0 = Fetch64(s); - ulong a1 = Fetch64(s + 8); - ulong a2 = Fetch64(s + 16); - ulong a3 = Fetch64(s + 24); - ulong a4 = Fetch64(s + 32); - ulong a5 = Fetch64(s + 40); - ulong a6 = Fetch64(s + 48); - ulong a7 = Fetch64(s + 56); - x += a0 + a1; - y += a2; - z += a3; - v_first += a4; - v_second += a5 + a1; - w_first += a6; - w_second += a7; - - x = Rotate64(x, 26); - x *= 9; - y = Rotate64(y, 29); - z *= mul; - v_first = Rotate64(v_first, 33); - v_second = Rotate64(v_second, 30); - w_first ^= x; - w_first *= 9; - z = Rotate64(z, 32); - z += w_second; - w_second += z; - z *= 9; - swap(ref u, ref y); - - z += a0 + a6; - v_first += a2; - v_second += a3; - w_first += a4; - w_second += a5 + a6; - x += a1; - y += a7; - - y += v_first; - v_first += x - y; - v_second += w_first; - w_first += v_second; - w_second += x - y; - x += w_second; - w_second = Rotate64(w_second, 34); - swap(ref u, ref z); - s += 64; - } - while (s != end); - - // Make s point to the last 64 bytes of input. - s = last64; - u *= 9; - v_second = Rotate64(v_second, 28); - v_first = Rotate64(v_first, 20); - w_first += (len - 1) & 63; - u += y; - y += u; - x = Rotate64(y - x + v_first + Fetch64(s + 8), 37) * mul; - y = Rotate64(y ^ v_second ^ Fetch64(s + 48), 42) * mul; - x ^= w_second * 9; - y += v_first + Fetch64(s + 40); - z = Rotate64(z + w_first, 33) * mul; - WeakHashLen32WithSeeds(s, v_second * mul, x + w_first, out v_first, out v_second); - WeakHashLen32WithSeeds(s + 32, z + w_second, y + Fetch64(s + 16), out w_first, out w_second); - return H(HashLen16(v_first + x, w_first ^ y, mul) + z - u, H(v_second + y, w_second + z, k2, 30) ^ x, k2, 31); - } - } - - #endregion - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/FarmHash.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/FarmHash.cs.meta deleted file mode 100644 index a0f99d4..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/FarmHash.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 97eed140914d52943ad6955224ce4577 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/GuidBits.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/GuidBits.cs deleted file mode 100644 index edf2987..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/GuidBits.cs +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.InteropServices; - -namespace MessagePack.Internal -{ - [StructLayout(LayoutKind.Explicit, Pack = 1)] - internal struct GuidBits - { - [FieldOffset(0)] - public readonly Guid Value; - - [FieldOffset(0)] - public readonly byte Byte0; - [FieldOffset(1)] - public readonly byte Byte1; - [FieldOffset(2)] - public readonly byte Byte2; - [FieldOffset(3)] - public readonly byte Byte3; - [FieldOffset(4)] - public readonly byte Byte4; - [FieldOffset(5)] - public readonly byte Byte5; - [FieldOffset(6)] - public readonly byte Byte6; - [FieldOffset(7)] - public readonly byte Byte7; - [FieldOffset(8)] - public readonly byte Byte8; - [FieldOffset(9)] - public readonly byte Byte9; - [FieldOffset(10)] - public readonly byte Byte10; - [FieldOffset(11)] - public readonly byte Byte11; - [FieldOffset(12)] - public readonly byte Byte12; - [FieldOffset(13)] - public readonly byte Byte13; - [FieldOffset(14)] - public readonly byte Byte14; - [FieldOffset(15)] - public readonly byte Byte15; - - // string.Join(", ", Enumerable.Range(0, 256).Select(x => (int)BitConverter.ToString(new byte[] { (byte)x }).ToLower()[0])) - private static ReadOnlySpan GetByteToHexStringHigh() => new byte[256] { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 57, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102 }; - - // string.Join(", ", Enumerable.Range(0, 256).Select(x => (int)BitConverter.ToString(new byte[] { (byte)x }).ToLower()[1])) - private static ReadOnlySpan GetByteToHexStringLow() => new byte[256] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102 }; - - public GuidBits(ref Guid value) - { - this = default(GuidBits); - this.Value = value; - } - - // 4-pattern, lower/upper and '-' or no - public GuidBits(ReadOnlySpan utf8string) - { - this = default(GuidBits); - - // 32 - if (utf8string.Length == 32) - { - if (BitConverter.IsLittleEndian) - { - this.Byte0 = Parse(utf8string, 6); - this.Byte1 = Parse(utf8string, 4); - this.Byte2 = Parse(utf8string, 2); - this.Byte3 = Parse(utf8string, 0); - - this.Byte4 = Parse(utf8string, 10); - this.Byte5 = Parse(utf8string, 8); - - this.Byte6 = Parse(utf8string, 14); - this.Byte7 = Parse(utf8string, 12); - } - else - { - this.Byte0 = Parse(utf8string, 0); - this.Byte1 = Parse(utf8string, 2); - this.Byte2 = Parse(utf8string, 4); - this.Byte3 = Parse(utf8string, 6); - - this.Byte4 = Parse(utf8string, 8); - this.Byte5 = Parse(utf8string, 10); - - this.Byte6 = Parse(utf8string, 12); - this.Byte7 = Parse(utf8string, 14); - } - - this.Byte8 = Parse(utf8string, 16); - this.Byte9 = Parse(utf8string, 18); - - this.Byte10 = Parse(utf8string, 20); - this.Byte11 = Parse(utf8string, 22); - this.Byte12 = Parse(utf8string, 24); - this.Byte13 = Parse(utf8string, 26); - this.Byte14 = Parse(utf8string, 28); - this.Byte15 = Parse(utf8string, 30); - return; - } - else if (utf8string.Length == 36) - { - // '-' => 45 - if (BitConverter.IsLittleEndian) - { - this.Byte0 = Parse(utf8string, 6); - this.Byte1 = Parse(utf8string, 4); - this.Byte2 = Parse(utf8string, 2); - this.Byte3 = Parse(utf8string, 0); - - if (utf8string[8] != '-') - { - goto ERROR; - } - - this.Byte4 = Parse(utf8string, 11); - this.Byte5 = Parse(utf8string, 9); - - if (utf8string[13] != '-') - { - goto ERROR; - } - - this.Byte6 = Parse(utf8string, 16); - this.Byte7 = Parse(utf8string, 14); - } - else - { - this.Byte0 = Parse(utf8string, 0); - this.Byte1 = Parse(utf8string, 2); - this.Byte2 = Parse(utf8string, 4); - this.Byte3 = Parse(utf8string, 6); - - if (utf8string[8] != '-') - { - goto ERROR; - } - - this.Byte4 = Parse(utf8string, 9); - this.Byte5 = Parse(utf8string, 11); - - if (utf8string[13] != '-') - { - goto ERROR; - } - - this.Byte6 = Parse(utf8string, 14); - this.Byte7 = Parse(utf8string, 16); - } - - if (utf8string[18] != '-') - { - goto ERROR; - } - - this.Byte8 = Parse(utf8string, 19); - this.Byte9 = Parse(utf8string, 21); - - if (utf8string[23] != '-') - { - goto ERROR; - } - - this.Byte10 = Parse(utf8string, 24); - this.Byte11 = Parse(utf8string, 26); - this.Byte12 = Parse(utf8string, 28); - this.Byte13 = Parse(utf8string, 30); - this.Byte14 = Parse(utf8string, 32); - this.Byte15 = Parse(utf8string, 34); - return; - } - -ERROR: - throw new MessagePackSerializationException("Invalid Guid Pattern."); - } - -#if !UNITY_2018_3_OR_NEWER - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] -#endif - private static byte Parse(ReadOnlySpan bytes, int highOffset) - { - return unchecked((byte)((SwitchParse(bytes[highOffset]) * 16) + SwitchParse(bytes[highOffset + 1]))); - } - -#if !UNITY_2018_3_OR_NEWER - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] -#endif - private static byte SwitchParse(byte b) - { - // '0'(48) ~ '9'(57) => -48 - // 'A'(65) ~ 'F'(70) => -55 - // 'a'(97) ~ 'f'(102) => -87 - switch (b) - { - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - return unchecked((byte)(b - 48)); - case 65: - case 66: - case 67: - case 68: - case 69: - case 70: - return unchecked((byte)(b - 55)); - case 97: - case 98: - case 99: - case 100: - case 101: - case 102: - return unchecked((byte)(b - 87)); - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - case 19: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - case 27: - case 28: - case 29: - case 30: - case 31: - case 32: - case 33: - case 34: - case 35: - case 36: - case 37: - case 38: - case 39: - case 40: - case 41: - case 42: - case 43: - case 44: - case 45: - case 46: - case 47: - case 58: - case 59: - case 60: - case 61: - case 62: - case 63: - case 64: - case 71: - case 72: - case 73: - case 74: - case 75: - case 76: - case 77: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 84: - case 85: - case 86: - case 87: - case 88: - case 89: - case 90: - case 91: - case 92: - case 93: - case 94: - case 95: - case 96: - default: - throw new MessagePackSerializationException("Invalid Guid Pattern."); - } - } - - // 4(x2) - 2(x2) - 2(x2) - 2(x2) - 6(x2) - public void Write(Span buffer) - { - var high = GetByteToHexStringHigh(); - var low = GetByteToHexStringLow(); - - if (BitConverter.IsLittleEndian) - { - // int(_a) - buffer[6] = high[this.Byte0]; - buffer[7] = low[this.Byte0]; - buffer[4] = high[this.Byte1]; - buffer[5] = low[this.Byte1]; - buffer[2] = high[this.Byte2]; - buffer[3] = low[this.Byte2]; - buffer[0] = high[this.Byte3]; - buffer[1] = low[this.Byte3]; - - buffer[8] = (byte)'-'; - - // short(_b) - buffer[11] = high[this.Byte4]; - buffer[12] = low[this.Byte4]; - buffer[9] = high[this.Byte5]; - buffer[10] = low[this.Byte5]; - - buffer[13] = (byte)'-'; - - // short(_c) - buffer[16] = high[this.Byte6]; - buffer[17] = low[this.Byte6]; - buffer[14] = high[this.Byte7]; - buffer[15] = low[this.Byte7]; - } - else - { - buffer[0] = high[this.Byte0]; - buffer[1] = low[this.Byte0]; - buffer[2] = high[this.Byte1]; - buffer[3] = low[this.Byte1]; - buffer[4] = high[this.Byte2]; - buffer[5] = low[this.Byte2]; - buffer[6] = high[this.Byte3]; - buffer[7] = low[this.Byte3]; - - buffer[8] = (byte)'-'; - - buffer[9] = high[this.Byte4]; - buffer[10] = low[this.Byte4]; - buffer[11] = high[this.Byte5]; - buffer[12] = low[this.Byte5]; - - buffer[13] = (byte)'-'; - - buffer[14] = high[this.Byte6]; - buffer[15] = low[this.Byte6]; - buffer[16] = high[this.Byte7]; - buffer[17] = low[this.Byte7]; - } - - buffer[18] = (byte)'-'; - - buffer[19] = high[this.Byte8]; - buffer[20] = low[this.Byte8]; - buffer[21] = high[this.Byte9]; - buffer[22] = low[this.Byte9]; - - buffer[23] = (byte)'-'; - - buffer[24] = high[this.Byte10]; - buffer[25] = low[this.Byte10]; - buffer[26] = high[this.Byte11]; - buffer[27] = low[this.Byte11]; - buffer[28] = high[this.Byte12]; - buffer[29] = low[this.Byte12]; - buffer[30] = high[this.Byte13]; - buffer[31] = low[this.Byte13]; - buffer[32] = high[this.Byte14]; - buffer[33] = low[this.Byte14]; - buffer[34] = high[this.Byte15]; - buffer[35] = low[this.Byte15]; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/GuidBits.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/GuidBits.cs.meta deleted file mode 100644 index 8786bd8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/GuidBits.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d68edf2bf3e742a4393af6f3e17345db -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ILGeneratorExtensions.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ILGeneratorExtensions.cs deleted file mode 100644 index aabada1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ILGeneratorExtensions.cs +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Internal -{ - internal struct ArgumentField - { - private readonly int i; - private readonly bool @ref; - private readonly ILGenerator il; - - public ArgumentField(ILGenerator il, int i, bool @ref = false) - { - this.il = il; - this.i = i; - this.@ref = @ref; - } - - public ArgumentField(ILGenerator il, int i, Type type) - { - this.il = il; - this.i = i; - TypeInfo ti = type.GetTypeInfo(); - this.@ref = (ti.IsClass || ti.IsInterface || ti.IsAbstract) ? false : true; - } - - public void EmitLoad() - { - if (this.@ref) - { - this.il.EmitLdarga(this.i); - } - else - { - this.il.EmitLdarg(this.i); - } - } - - public void EmitLdarg() - { - this.il.EmitLdarg(this.i); - } - - public void EmitLdarga() - { - this.il.EmitLdarga(this.i); - } - - public void EmitStore() - { - this.il.EmitStarg(this.i); - } - } - - /// - /// Provides optimized generation code and helpers. - /// - internal static class ILGeneratorExtensions - { - /// - /// Loads the local variable at a specific index onto the evaluation stack. - /// - public static void EmitLdloc(this ILGenerator il, int index) - { - switch (index) - { - case 0: - il.Emit(OpCodes.Ldloc_0); - break; - case 1: - il.Emit(OpCodes.Ldloc_1); - break; - case 2: - il.Emit(OpCodes.Ldloc_2); - break; - case 3: - il.Emit(OpCodes.Ldloc_3); - break; - default: - if (index <= 255) - { - il.Emit(OpCodes.Ldloc_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldloc, (short)index); - } - - break; - } - } - - public static void EmitLdloc(this ILGenerator il, LocalBuilder local) - { - EmitLdloc(il, local.LocalIndex); - } - - /// - /// Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index. - /// - public static void EmitStloc(this ILGenerator il, int index) - { - switch (index) - { - case 0: - il.Emit(OpCodes.Stloc_0); - break; - case 1: - il.Emit(OpCodes.Stloc_1); - break; - case 2: - il.Emit(OpCodes.Stloc_2); - break; - case 3: - il.Emit(OpCodes.Stloc_3); - break; - default: - if (index <= 255) - { - il.Emit(OpCodes.Stloc_S, (byte)index); - } - else - { - il.Emit(OpCodes.Stloc, (short)index); - } - - break; - } - } - - public static void EmitStloc(this ILGenerator il, LocalBuilder local) - { - EmitStloc(il, local.LocalIndex); - } - - /// - /// Loads the address of the local variable at a specific index onto the evaluation statck. - /// - public static void EmitLdloca(this ILGenerator il, int index) - { - if (index <= 255) - { - il.Emit(OpCodes.Ldloca_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldloca, (short)index); - } - } - - public static void EmitLdloca(this ILGenerator il, LocalBuilder local) - { - EmitLdloca(il, local.LocalIndex); - } - - public static void EmitTrue(this ILGenerator il) - { - EmitBoolean(il, true); - } - - public static void EmitFalse(this ILGenerator il) - { - EmitBoolean(il, false); - } - - public static void EmitBoolean(this ILGenerator il, bool value) - { - EmitLdc_I4(il, value ? 1 : 0); - } - - /// - /// Pushes a supplied value of type int32 onto the evaluation stack as an int32. - /// - public static void EmitLdc_I4(this ILGenerator il, int value) - { - switch (value) - { - case -1: - il.Emit(OpCodes.Ldc_I4_M1); - break; - 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; - default: - if (value >= -128 && value <= 127) - { - il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); - } - else - { - il.Emit(OpCodes.Ldc_I4, value); - } - - break; - } - } - - public static void EmitUnboxOrCast(this ILGenerator il, Type type) - { - if (type.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Unbox_Any, type); - } - else - { - il.Emit(OpCodes.Castclass, type); - } - } - - public static void EmitBoxOrDoNothing(this ILGenerator il, Type type) - { - if (type.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Box, type); - } - } - - public static void EmitLdarg(this ILGenerator il, int index) - { - switch (index) - { - case 0: - il.Emit(OpCodes.Ldarg_0); - break; - case 1: - il.Emit(OpCodes.Ldarg_1); - break; - case 2: - il.Emit(OpCodes.Ldarg_2); - break; - case 3: - il.Emit(OpCodes.Ldarg_3); - break; - default: - if (index <= 255) - { - il.Emit(OpCodes.Ldarg_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldarg, index); - } - - break; - } - } - - public static void EmitLoadThis(this ILGenerator il) - { - EmitLdarg(il, 0); - } - - public static void EmitLdarga(this ILGenerator il, int index) - { - if (index <= 255) - { - il.Emit(OpCodes.Ldarga_S, (byte)index); - } - else - { - il.Emit(OpCodes.Ldarga, index); - } - } - - public static void EmitStarg(this ILGenerator il, int index) - { - if (index <= 255) - { - il.Emit(OpCodes.Starg_S, (byte)index); - } - else - { - il.Emit(OpCodes.Starg, index); - } - } - - /// - /// Helper for Pop op. - /// - public static void EmitPop(this ILGenerator il, int count) - { - for (int i = 0; i < count; i++) - { - il.Emit(OpCodes.Pop); - } - } - - public static void EmitCall(this ILGenerator il, MethodInfo methodInfo) - { - if (methodInfo.IsFinal || !methodInfo.IsVirtual) - { - il.Emit(OpCodes.Call, methodInfo); - } - else - { - il.Emit(OpCodes.Callvirt, methodInfo); - } - } - - public static void EmitLdfld(this ILGenerator il, FieldInfo fieldInfo) - { - il.Emit(OpCodes.Ldfld, fieldInfo); - } - - public static void EmitLdsfld(this ILGenerator il, FieldInfo fieldInfo) - { - il.Emit(OpCodes.Ldsfld, fieldInfo); - } - - public static void EmitRet(this ILGenerator il) - { - il.Emit(OpCodes.Ret); - } - - public static void EmitIntZeroReturn(this ILGenerator il) - { - il.EmitLdc_I4(0); - il.Emit(OpCodes.Ret); - } - - public static void EmitNullReturn(this ILGenerator il) - { - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Ret); - } - - public static void EmitULong(this ILGenerator il, ulong value) - { - il.Emit(OpCodes.Ldc_I8, unchecked((long)value)); - } - - public static void EmitThrowNotimplemented(this ILGenerator il) - { - il.Emit(OpCodes.Newobj, typeof(System.NotImplementedException).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0)); - il.Emit(OpCodes.Throw); - } - - /// for var i = 0, i ..., i++. - public static void EmitIncrementFor(this ILGenerator il, LocalBuilder conditionGreater, Action emitBody) - { - Label loopBegin = il.DefineLabel(); - Label condtionLabel = il.DefineLabel(); - - // var i = 0 - LocalBuilder forI = il.DeclareLocal(typeof(int)); - il.EmitLdc_I4(0); - il.EmitStloc(forI); - il.Emit(OpCodes.Br, condtionLabel); - - il.MarkLabel(loopBegin); - emitBody(forI); - - // i++ - il.EmitLdloc(forI); - il.EmitLdc_I4(1); - il.Emit(OpCodes.Add); - il.EmitStloc(forI); - - //// i < *** - il.MarkLabel(condtionLabel); - il.EmitLdloc(forI); - il.EmitLdloc(conditionGreater); - il.Emit(OpCodes.Blt, loopBegin); - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ILGeneratorExtensions.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ILGeneratorExtensions.cs.meta deleted file mode 100644 index 7319fd4..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ILGeneratorExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 581e7074a007a6548a5e8408a4dad6dc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ReflectionExtensions.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ReflectionExtensions.cs deleted file mode 100644 index dba6213..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ReflectionExtensions.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace MessagePack.Internal -{ - internal static class ReflectionExtensions - { - public static bool IsNullable(this System.Reflection.TypeInfo type) - { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Nullable<>); - } - - public static bool IsPublic(this System.Reflection.TypeInfo type) - { - return type.IsPublic; - } - - public static bool IsAnonymous(this System.Reflection.TypeInfo type) - { - return type.Namespace == null - && type.IsSealed - && (type.Name.StartsWith("<>f__AnonymousType", StringComparison.Ordinal) - || type.Name.StartsWith("<>__AnonType", StringComparison.Ordinal) - || type.Name.StartsWith("VB$AnonymousType_", StringComparison.Ordinal)) - && type.IsDefined(typeof(CompilerGeneratedAttribute), false); - } - - public static bool IsIndexer(this System.Reflection.PropertyInfo propertyInfo) - { - return propertyInfo.GetIndexParameters().Length > 0; - } - - public static bool IsConstructedGenericType(this System.Reflection.TypeInfo type) - { - return type.AsType().IsConstructedGenericType; - } - - public static MethodInfo GetGetMethod(this PropertyInfo propInfo) - { - return propInfo.GetMethod; - } - - public static MethodInfo GetSetMethod(this PropertyInfo propInfo) - { - return propInfo.SetMethod; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ReflectionExtensions.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ReflectionExtensions.cs.meta deleted file mode 100644 index 459e775..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ReflectionExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a6682a58039cc664c9e66b2d4b02d4d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/RuntimeTypeHandleEqualityComparer.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/RuntimeTypeHandleEqualityComparer.cs deleted file mode 100644 index 7f6c888..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/RuntimeTypeHandleEqualityComparer.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; - -namespace MessagePack.Internal -{ - // This code is used in generated code so must be public. - - // RuntimeTypeHandle can embed directly by OpCodes.Ldtoken - // It does not implements IEquatable(but GetHashCode and Equals is implemented) so needs this to avoid boxing. - public class RuntimeTypeHandleEqualityComparer : IEqualityComparer - { - public static readonly IEqualityComparer Default = new RuntimeTypeHandleEqualityComparer(); - - private RuntimeTypeHandleEqualityComparer() - { - } - - public bool Equals(RuntimeTypeHandle x, RuntimeTypeHandle y) - { - return x.Equals(y); - } - - public int GetHashCode(RuntimeTypeHandle obj) - { - return obj.GetHashCode(); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/RuntimeTypeHandleEqualityComparer.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/RuntimeTypeHandleEqualityComparer.cs.meta deleted file mode 100644 index 8479df5..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/RuntimeTypeHandleEqualityComparer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bceda592765280b4f8cb470f1ed9c532 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/Sequence`1.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/Sequence`1.cs deleted file mode 100644 index 9fe752d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/Sequence`1.cs +++ /dev/null @@ -1,574 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* Original license and copyright from file copied from https://github.com/AArnott/Nerdbank.Streams/blob/d656899be26d4d7c72c11c9232b4952c64a89bcb/src/Nerdbank.Streams/Sequence%601.cs - * Copyright (c) Andrew Arnott. All rights reserved. - * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. -*/ - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Nerdbank.Streams -{ - /// - /// Manages a sequence of elements, readily castable as a . - /// - /// The type of element stored by the sequence. - /// - /// Instance members are not thread-safe. - /// - [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] - internal class Sequence : IBufferWriter, IDisposable - { - private static readonly int DefaultLengthFromArrayPool = 1 + (4095 / Marshal.SizeOf()); - - private readonly Stack segmentPool = new Stack(); - - private readonly MemoryPool memoryPool; - - private readonly ArrayPool arrayPool; - - private SequenceSegment first; - - private SequenceSegment last; - - /// - /// Initializes a new instance of the class - /// that uses a private for recycling arrays. - /// - public Sequence() - : this(ArrayPool.Create()) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The pool to use for recycling backing arrays. - public Sequence(MemoryPool memoryPool) - { - Requires.NotNull(memoryPool, nameof(memoryPool)); - this.memoryPool = memoryPool; - } - - /// - /// Initializes a new instance of the class. - /// - /// The pool to use for recycling backing arrays. - public Sequence(ArrayPool arrayPool) - { - Requires.NotNull(arrayPool, nameof(arrayPool)); - this.arrayPool = arrayPool; - } - - /// - /// Gets or sets the minimum length for any array allocated as a segment in the sequence. - /// Any non-positive value allows the pool to determine the length of the array. - /// - /// The default value is 0. - /// - /// - /// Each time or is called, - /// previously allocated memory is used if it is large enough to satisfy the length demand. - /// If new memory must be allocated, the argument to one of these methods typically dictate - /// the length of array to allocate. When the caller uses very small values (just enough for its immediate need) - /// but the high level scenario can predict that a large amount of memory will be ultimately required, - /// it can be advisable to set this property to a value such that just a few larger arrays are allocated - /// instead of many small ones. - /// - /// - /// The in use may itself have a minimum array length as well, - /// in which case the higher of the two minimums dictate the minimum array size that will be allocated. - /// - /// - public int MinimumSpanLength { get; set; } = 0; - - /// - /// Gets this sequence expressed as a . - /// - /// A read only sequence representing the data in this object. - public ReadOnlySequence AsReadOnlySequence => this; - - /// - /// Gets the length of the sequence. - /// - public long Length => this.AsReadOnlySequence.Length; - - /// - /// Gets the value to display in a debugger datatip. - /// - private string DebuggerDisplay => $"Length: {this.AsReadOnlySequence.Length}"; - - /// - /// Expresses this sequence as a . - /// - /// The sequence to convert. - public static implicit operator ReadOnlySequence(Sequence sequence) - { - return sequence.first != null - ? new ReadOnlySequence(sequence.first, sequence.first.Start, sequence.last, sequence.last.End) - : ReadOnlySequence.Empty; - } - - /// - /// Removes all elements from the sequence from its beginning to the specified position, - /// considering that data to have been fully processed. - /// - /// - /// The position of the first element that has not yet been processed. - /// This is typically after reading all elements from that instance. - /// - public void AdvanceTo(SequencePosition position) - { - var firstSegment = (SequenceSegment)position.GetObject(); - int firstIndex = position.GetInteger(); - - // Before making any mutations, confirm that the block specified belongs to this sequence. - var current = this.first; - while (current != firstSegment && current != null) - { - current = current.Next; - } - - Requires.Argument(current != null, nameof(position), "Position does not represent a valid position in this sequence."); - - // Also confirm that the position is not a prior position in the block. - Requires.Argument(firstIndex >= current.Start, nameof(position), "Position must not be earlier than current position."); - - // Now repeat the loop, performing the mutations. - current = this.first; - while (current != firstSegment) - { - current = this.RecycleAndGetNext(current); - } - - firstSegment.AdvanceTo(firstIndex); - - if (firstSegment.Length == 0) - { - firstSegment = this.RecycleAndGetNext(firstSegment); - } - - this.first = firstSegment; - - if (this.first == null) - { - this.last = null; - } - } - - /// - /// Advances the sequence to include the specified number of elements initialized into memory - /// returned by a prior call to . - /// - /// The number of elements written into memory. - public void Advance(int count) - { - SequenceSegment last = this.last; - Verify.Operation(last != null, "Cannot advance before acquiring memory."); - last.Advance(count); - } - - /// - /// Gets writable memory that can be initialized and added to the sequence via a subsequent call to . - /// - /// The size of the memory required, or 0 to just get a convenient (non-empty) buffer. - /// The requested memory. - public Memory GetMemory(int sizeHint) => this.GetSegment(sizeHint).RemainingMemory; - - /// - /// Gets writable memory that can be initialized and added to the sequence via a subsequent call to . - /// - /// The size of the memory required, or 0 to just get a convenient (non-empty) buffer. - /// The requested memory. - public Span GetSpan(int sizeHint) => this.GetSegment(sizeHint).RemainingSpan; - - /// - /// Clears the entire sequence, recycles associated memory into pools, - /// and resets this instance for reuse. - /// This invalidates any previously produced by this instance. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public void Dispose() => this.Reset(); - - /// - /// Clears the entire sequence and recycles associated memory into pools. - /// This invalidates any previously produced by this instance. - /// - public void Reset() - { - var current = this.first; - while (current != null) - { - current = this.RecycleAndGetNext(current); - } - - this.first = this.last = null; - } - - private SequenceSegment GetSegment(int sizeHint) - { - Requires.Range(sizeHint >= 0, nameof(sizeHint)); - int? minBufferSize = null; - if (sizeHint == 0) - { - if (this.last == null || this.last.WritableBytes == 0) - { - // We're going to need more memory. Take whatever size the pool wants to give us. - minBufferSize = -1; - } - } - else - { - sizeHint = Math.Max(this.MinimumSpanLength, sizeHint); - if (this.last == null || this.last.WritableBytes < sizeHint) - { - minBufferSize = sizeHint; - } - } - - if (minBufferSize.HasValue) - { - var segment = this.segmentPool.Count > 0 ? this.segmentPool.Pop() : new SequenceSegment(); - if (this.arrayPool != null) - { - segment.Assign(this.arrayPool.Rent(minBufferSize.Value == -1 ? DefaultLengthFromArrayPool : minBufferSize.Value)); - } - else - { - segment.Assign(this.memoryPool.Rent(minBufferSize.Value)); - } - - this.Append(segment); - } - - return this.last; - } - - private void Append(SequenceSegment segment) - { - if (this.last == null) - { - this.first = this.last = segment; - } - else - { - if (this.last.Length > 0) - { - // Add a new block. - this.last.SetNext(segment); - } - else - { - // The last block is completely unused. Replace it instead of appending to it. - var current = this.first; - if (this.first != this.last) - { - while (current.Next != this.last) - { - current = current.Next; - } - } - else - { - this.first = segment; - } - - current.SetNext(segment); - this.RecycleAndGetNext(this.last); - } - - this.last = segment; - } - } - - private SequenceSegment RecycleAndGetNext(SequenceSegment segment) - { - var recycledSegment = segment; - segment = segment.Next; - recycledSegment.ResetMemory(this.arrayPool); - this.segmentPool.Push(recycledSegment); - return segment; - } - - private class SequenceSegment : ReadOnlySequenceSegment - { - /// - /// A value indicating whether the element may contain references (and thus must be cleared). - /// - private static readonly bool MayContainReferences = !typeof(T).GetTypeInfo().IsPrimitive; - - /// - /// Gets the backing array, when using an instead of a . - /// - private T[] array; - - /// - /// Gets the position within where the data starts. - /// - /// This may be nonzero as a result of calling . - internal int Start { get; private set; } - - /// - /// Gets the position within where the data ends. - /// - internal int End { get; private set; } - - /// - /// Gets the tail of memory that has not yet been committed. - /// - internal Memory RemainingMemory => this.AvailableMemory.Slice(this.End); - - /// - /// Gets the tail of memory that has not yet been committed. - /// - internal Span RemainingSpan => this.AvailableMemory.Span.Slice(this.End); - - /// - /// Gets the tracker for the underlying array for this segment, which can be used to recycle the array when we're disposed of. - /// Will be null if using an array pool, in which case the memory is held by . - /// - internal IMemoryOwner MemoryOwner { get; private set; } - - /// - /// Gets the full memory owned by the . - /// - internal Memory AvailableMemory => this.array ?? this.MemoryOwner?.Memory ?? default; - - /// - /// Gets the number of elements that are committed in this segment. - /// - internal int Length => this.End - this.Start; - - /// - /// Gets the amount of writable bytes in this segment. - /// It is the amount of bytes between and . - /// - internal int WritableBytes => this.AvailableMemory.Length - this.End; - - /// - /// Gets or sets the next segment in the singly linked list of segments. - /// - internal new SequenceSegment Next - { - get => (SequenceSegment)base.Next; - set => base.Next = value; - } - - /// - /// Assigns this (recyclable) segment a new area in memory. - /// - /// The memory and a means to recycle it. - internal void Assign(IMemoryOwner memoryOwner) - { - this.MemoryOwner = memoryOwner; - this.Memory = memoryOwner.Memory; - } - - /// - /// Assigns this (recyclable) segment a new area in memory. - /// - /// An array drawn from an . - internal void Assign(T[] array) - { - this.array = array; - this.Memory = array; - } - - /// - /// Clears all fields in preparation to recycle this instance. - /// - internal void ResetMemory(ArrayPool arrayPool) - { - this.ClearReferences(this.Start, this.End); - this.Memory = default; - this.Next = null; - this.RunningIndex = 0; - this.Start = 0; - this.End = 0; - if (this.array != null) - { - arrayPool.Return(this.array); - this.array = null; - } - else - { - this.MemoryOwner?.Dispose(); - this.MemoryOwner = null; - } - } - - /// - /// Adds a new segment after this one. - /// - /// The next segment in the linked list. - internal void SetNext(SequenceSegment segment) - { - Debug.Assert(segment != null, "Null not allowed."); - this.Next = segment; - segment.RunningIndex = this.RunningIndex + this.Start + this.Length; - - // When setting Memory, we start with index 0 instead of this.Start because - // the first segment has an explicit index set anyway, - // and we don't want to double-count it here. - this.Memory = this.AvailableMemory.Slice(0, this.Start + this.Length); - } - - /// - /// Commits more elements as written in this segment. - /// - /// The number of elements written. - internal void Advance(int count) - { - Requires.Range(count >= 0 && this.End + count <= this.Memory.Length, nameof(count)); - this.End += count; - } - - /// - /// Removes some elements from the start of this segment. - /// - /// The number of elements to ignore from the start of the underlying array. - internal void AdvanceTo(int offset) - { - Debug.Assert(offset >= this.Start, "Trying to rewind."); - this.ClearReferences(this.Start, offset - this.Start); - this.Start = offset; - } - - private void ClearReferences(int startIndex, int length) - { - // Clear the array to allow the objects to be GC'd. - // Reference types need to be cleared. Value types can be structs with reference type members too, so clear everything. - if (MayContainReferences) - { - this.AvailableMemory.Span.Slice(startIndex, length).Clear(); - } - } - } - } - - internal static class Requires - { - /// - /// Throws an if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Range(bool condition, string parameterName, string message = null) - { - if (!condition) - { - FailRange(parameterName, message); - } - } - - /// - /// Throws an if a condition does not evaluate to true. - /// - /// Nothing. This method always throws. - [DebuggerStepThrough] - public static Exception FailRange(string parameterName, string message = null) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentOutOfRangeException(parameterName); - } - else - { - throw new ArgumentOutOfRangeException(parameterName, message); - } - } - - /// - /// Throws an exception if the specified parameter's value is null. - /// - /// The type of the parameter. - /// The value of the argument. - /// The name of the parameter to include in any thrown exception. - /// The value of the parameter. - /// Thrown if is null. - [DebuggerStepThrough] - public static T NotNull(T value, string parameterName) - where T : class // ensures value-types aren't passed to a null checking method - { - if (value == null) - { - throw new ArgumentNullException(parameterName); - } - - return value; - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message) - { - if (!condition) - { - throw new ArgumentException(message, parameterName); - } - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message, object arg1) - { - if (!condition) - { - throw new ArgumentException(String.Format(message, arg1), parameterName); - } - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message, object arg1, object arg2) - { - if (!condition) - { - throw new ArgumentException(String.Format(message, arg1, arg2), parameterName); - } - } - - /// - /// Throws an ArgumentException if a condition does not evaluate to true. - /// - [DebuggerStepThrough] - public static void Argument(bool condition, string parameterName, string message, params object[] args) - { - if (!condition) - { - throw new ArgumentException(String.Format(message, args), parameterName); - } - } - } - - /// - /// Common runtime checks that throw exceptions upon failure. - /// - internal static partial class Verify - { - /// - /// Throws an if a condition is false. - /// - [DebuggerStepThrough] - internal static void Operation(bool condition, string message) - { - if (!condition) - { - throw new InvalidOperationException(message); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/Sequence`1.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/Sequence`1.cs.meta deleted file mode 100644 index 96a9f88..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/Sequence`1.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 46a3d0af338351d4b897b1323a92233a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs deleted file mode 100644 index 74d9546..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.CompilerServices; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Internal -{ - /// - /// A dictionary where is the key, and a configurable type - /// that is thread-safe to read and write, allowing concurrent reads and exclusive writes. - /// - /// The type of value stored in the dictionary. - internal class ThreadsafeTypeKeyHashTable - { - private Entry[] buckets; - private int size; // only use in writer lock - - private readonly object writerLock = new object(); - private readonly float loadFactor; - - // IEqualityComparer.Equals is overhead if key only Type, don't use it. - //// readonly IEqualityComparer comparer; - - public ThreadsafeTypeKeyHashTable(int capacity = 4, float loadFactor = 0.75f) - { - var tableSize = CalculateCapacity(capacity, loadFactor); - this.buckets = new Entry[tableSize]; - this.loadFactor = loadFactor; - } - - public bool TryAdd(Type key, TValue value) - { - return this.TryAdd(key, _ => value); // create lambda capture - } - - public bool TryAdd(Type key, Func valueFactory) - { - return this.TryAddInternal(key, valueFactory, out TValue _); - } - - private bool TryAddInternal(Type key, Func valueFactory, out TValue resultingValue) - { - lock (this.writerLock) - { - var nextCapacity = CalculateCapacity(this.size + 1, this.loadFactor); - - if (this.buckets.Length < nextCapacity) - { - // rehash - var nextBucket = new Entry[nextCapacity]; - for (int i = 0; i < this.buckets.Length; i++) - { - Entry e = this.buckets[i]; - while (e != null) - { - var newEntry = new Entry { Key = e.Key, Value = e.Value, Hash = e.Hash }; - this.AddToBuckets(nextBucket, key, newEntry, null, out resultingValue); - e = e.Next; - } - } - - // add entry(if failed to add, only do resize) - var successAdd = this.AddToBuckets(nextBucket, key, null, valueFactory, out resultingValue); - - // replace field(threadsafe for read) - VolatileWrite(ref this.buckets, nextBucket); - - if (successAdd) - { - this.size++; - } - - return successAdd; - } - else - { - // add entry(insert last is thread safe for read) - var successAdd = this.AddToBuckets(this.buckets, key, null, valueFactory, out resultingValue); - if (successAdd) - { - this.size++; - } - - return successAdd; - } - } - } - - private bool AddToBuckets(Entry[] buckets, Type newKey, Entry newEntryOrNull, Func valueFactory, out TValue resultingValue) - { - var h = (newEntryOrNull != null) ? newEntryOrNull.Hash : newKey.GetHashCode(); - if (buckets[h & (buckets.Length - 1)] == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref buckets[h & (buckets.Length - 1)], newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref buckets[h & (buckets.Length - 1)], new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - } - else - { - Entry searchLastEntry = buckets[h & (buckets.Length - 1)]; - while (true) - { - if (searchLastEntry.Key == newKey) - { - resultingValue = searchLastEntry.Value; - return false; - } - - if (searchLastEntry.Next == null) - { - if (newEntryOrNull != null) - { - resultingValue = newEntryOrNull.Value; - VolatileWrite(ref searchLastEntry.Next, newEntryOrNull); - } - else - { - resultingValue = valueFactory(newKey); - VolatileWrite(ref searchLastEntry.Next, new Entry { Key = newKey, Value = resultingValue, Hash = h }); - } - - break; - } - - searchLastEntry = searchLastEntry.Next; - } - } - - return true; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryGetValue(Type key, out TValue value) - { - Entry[] table = this.buckets; - var hash = key.GetHashCode(); - Entry entry = table[hash & table.Length - 1]; - - while (entry != null) - { - if (entry.Key == key) - { - value = entry.Value; - return true; - } - - entry = entry.Next; - } - - value = default(TValue); - return false; - } - - public TValue GetOrAdd(Type key, Func valueFactory) - { - TValue v; - if (this.TryGetValue(key, out v)) - { - return v; - } - - this.TryAddInternal(key, valueFactory, out v); - return v; - } - - private static int CalculateCapacity(int collectionSize, float loadFactor) - { - var initialCapacity = (int)(((float)collectionSize) / loadFactor); - var capacity = 1; - while (capacity < initialCapacity) - { - capacity <<= 1; - } - - if (capacity < 8) - { - return 8; - } - - return capacity; - } - - private static void VolatileWrite(ref Entry location, Entry value) - { -#if !UNITY_2018_3_OR_NEWER - System.Threading.Volatile.Write(ref location, value); -#elif UNITY_2018_3_OR_NEWER || NET_4_6 - System.Threading.Volatile.Write(ref location, value); -#else - System.Threading.Thread.MemoryBarrier(); - location = value; -#endif - } - - private static void VolatileWrite(ref Entry[] location, Entry[] value) - { -#if !UNITY_2018_3_OR_NEWER - System.Threading.Volatile.Write(ref location, value); -#elif UNITY_2018_3_OR_NEWER || NET_4_6 - System.Threading.Volatile.Write(ref location, value); -#else - System.Threading.Thread.MemoryBarrier(); - location = value; -#endif - } - - private class Entry - { -#pragma warning disable SA1401 // Fields should be private - internal Type Key; - internal TValue Value; - internal int Hash; - internal Entry Next; -#pragma warning restore SA1401 // Fields should be private - - // debug only - public override string ToString() - { - return this.Key + "(" + this.Count() + ")"; - } - - private int Count() - { - var count = 1; - Entry n = this; - while (n.Next != null) - { - count++; - n = n.Next; - } - - return count; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs.meta deleted file mode 100644 index 8629369..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/ThreadsafeTypeKeyHashTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 324a59f0b14af2544807199e055a1ac4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/TinyJsonReader.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/TinyJsonReader.cs deleted file mode 100644 index 8726306..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/TinyJsonReader.cs +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Globalization; -using System.IO; -using System.Text; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack -{ - /* simple, tiny JSON reader for MessagePackSerializer.FromJson. - * this is simple, compact and enough fast but not optimized extremely. */ - - internal enum TinyJsonToken - { - None, - StartObject, // { - EndObject, // } - StartArray, // [ - EndArray, // ] - Number, // -0~9 - String, // "___" - True, // true - False, // false - Null, // null - } - - internal enum ValueType : byte - { - Null, - True, - False, - Double, - Long, - ULong, - Decimal, - String, - } - - public class TinyJsonException : MessagePackSerializationException - { - public TinyJsonException(string message) - : base(message) - { - } - } - - internal class TinyJsonReader : IDisposable - { - private readonly TextReader reader; - private readonly bool disposeInnerReader; - private StringBuilder reusableBuilder; - - public TinyJsonToken TokenType { get; private set; } - - public ValueType ValueType { get; private set; } - - public double DoubleValue { get; private set; } - - public long LongValue { get; private set; } - - public ulong ULongValue { get; private set; } - - public decimal DecimalValue { get; private set; } - - public string StringValue { get; private set; } - - public TinyJsonReader(TextReader reader, bool disposeInnerReader = true) - { - this.reader = reader; - this.disposeInnerReader = disposeInnerReader; - } - - public bool Read() - { - this.ReadNextToken(); - this.ReadValue(); - return this.TokenType != TinyJsonToken.None; - } - - public void Dispose() - { - if (this.reader != null && this.disposeInnerReader) - { - this.reader.Dispose(); - } - - this.TokenType = TinyJsonToken.None; - this.ValueType = ValueType.Null; - } - - private void SkipWhiteSpace() - { - var c = this.reader.Peek(); - while (c != -1 && Char.IsWhiteSpace((char)c)) - { - this.reader.Read(); - c = this.reader.Peek(); - } - } - - private char ReadChar() - { - return (char)this.reader.Read(); - } - - private static bool IsWordBreak(char c) - { - switch (c) - { - case ' ': - case '{': - case '}': - case '[': - case ']': - case ',': - case ':': - case '\"': - return true; - default: - return false; - } - } - - private void ReadNextToken() - { - this.SkipWhiteSpace(); - - var intChar = this.reader.Peek(); - if (intChar == -1) - { - this.TokenType = TinyJsonToken.None; - return; - } - - var c = (char)intChar; - switch (c) - { - case '{': - this.TokenType = TinyJsonToken.StartObject; - return; - case '}': - this.TokenType = TinyJsonToken.EndObject; - return; - case '[': - this.TokenType = TinyJsonToken.StartArray; - return; - case ']': - this.TokenType = TinyJsonToken.EndArray; - return; - case '"': - this.TokenType = TinyJsonToken.String; - return; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - this.TokenType = TinyJsonToken.Number; - return; - case 't': - this.TokenType = TinyJsonToken.True; - return; - case 'f': - this.TokenType = TinyJsonToken.False; - return; - case 'n': - this.TokenType = TinyJsonToken.Null; - return; - case ',': - case ':': - this.reader.Read(); - this.ReadNextToken(); - return; - default: - throw new TinyJsonException("Invalid String:" + c); - } - } - - private void ReadValue() - { - this.ValueType = ValueType.Null; - - switch (this.TokenType) - { - case TinyJsonToken.None: - break; - case TinyJsonToken.StartObject: - case TinyJsonToken.EndObject: - case TinyJsonToken.StartArray: - case TinyJsonToken.EndArray: - this.reader.Read(); - break; - case TinyJsonToken.Number: - this.ReadNumber(); - break; - case TinyJsonToken.String: - this.ReadString(); - break; - case TinyJsonToken.True: - if (this.ReadChar() != 't') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'r') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'u') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'e') - { - throw new TinyJsonException("Invalid Token"); - } - - this.ValueType = ValueType.True; - break; - case TinyJsonToken.False: - if (this.ReadChar() != 'f') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'a') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'l') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 's') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'e') - { - throw new TinyJsonException("Invalid Token"); - } - - this.ValueType = ValueType.False; - break; - case TinyJsonToken.Null: - if (this.ReadChar() != 'n') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'u') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'l') - { - throw new TinyJsonException("Invalid Token"); - } - - if (this.ReadChar() != 'l') - { - throw new TinyJsonException("Invalid Token"); - } - - this.ValueType = ValueType.Null; - break; - default: - throw new MessagePackSerializationException("InvalidTokenState:" + this.TokenType); - } - } - - private void ReadNumber() - { - StringBuilder numberWord; - if (this.reusableBuilder == null) - { - this.reusableBuilder = new StringBuilder(); - numberWord = this.reusableBuilder; - } - else - { - numberWord = this.reusableBuilder; - numberWord.Length = 0; // Clear - } - - var isDouble = false; - var intChar = this.reader.Peek(); - while (intChar != -1 && !IsWordBreak((char)intChar)) - { - var c = this.ReadChar(); - numberWord.Append(c); - if (c == '.' || c == 'e' || c == 'E') - { - isDouble = true; - } - - intChar = this.reader.Peek(); - } - - var number = numberWord.ToString(); - if (isDouble) - { - double parsedDouble; - Double.TryParse(number, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); - this.ValueType = ValueType.Double; - this.DoubleValue = parsedDouble; - } - else - { - long parsedInt; - if (Int64.TryParse(number, NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out parsedInt)) - { - this.ValueType = ValueType.Long; - this.LongValue = parsedInt; - return; - } - - ulong parsedULong; - if (ulong.TryParse(number, NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out parsedULong)) - { - this.ValueType = ValueType.ULong; - this.ULongValue = parsedULong; - return; - } - - Decimal parsedDecimal; - if (decimal.TryParse(number, NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out parsedDecimal)) - { - this.ValueType = ValueType.Decimal; - this.DecimalValue = parsedDecimal; - return; - } - } - } - - private void ReadString() - { - this.reader.Read(); // skip ["] - - StringBuilder sb; - if (this.reusableBuilder == null) - { - this.reusableBuilder = new StringBuilder(); - sb = this.reusableBuilder; - } - else - { - sb = this.reusableBuilder; - sb.Length = 0; // Clear - } - - while (true) - { - if (this.reader.Peek() == -1) - { - throw new TinyJsonException("Invalid Json String"); - } - - var c = this.ReadChar(); - switch (c) - { - case '"': // endtoken - goto END; - case '\\': // escape character - if (this.reader.Peek() == -1) - { - throw new TinyJsonException("Invalid Json String"); - } - - c = this.ReadChar(); - switch (c) - { - case '"': - case '\\': - case '/': - sb.Append(c); - break; - case 'b': - sb.Append('\b'); - break; - case 'f': - sb.Append('\f'); - break; - case 'n': - sb.Append('\n'); - break; - case 'r': - sb.Append('\r'); - break; - case 't': - sb.Append('\t'); - break; - case 'u': - var hex = new char[4]; - hex[0] = this.ReadChar(); - hex[1] = this.ReadChar(); - hex[2] = this.ReadChar(); - hex[3] = this.ReadChar(); - sb.Append((char)Convert.ToInt32(new string(hex), 16)); - break; - } - - break; - default: // string - sb.Append(c); - break; - } - } - -END: - this.ValueType = ValueType.String; - this.StringValue = sb.ToString(); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/TinyJsonReader.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/TinyJsonReader.cs.meta deleted file mode 100644 index df16ecc..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/TinyJsonReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bd9d3de59693d9f49be777193cd4e846 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/UnsafeMemory.Low.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/UnsafeMemory.Low.cs deleted file mode 100644 index 39e1f5c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/UnsafeMemory.Low.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !UNITY_2018_3_OR_NEWER - -using System; -using System.Runtime.CompilerServices; - -namespace MessagePack.Internal -{ - /* for string key property name write optimization. */ - - public static class UnsafeMemory - { - public static readonly bool Is32Bit = IntPtr.Size == 4; - } - - public static partial class UnsafeMemory32 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw1(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw2(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(short*)pDst = *(short*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw3(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - *(short*)(pDst + 1) = *(short*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - } - - public static partial class UnsafeMemory64 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw1(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw2(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(short*)pDst = *(short*)pSrc; - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw3(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(byte*)pDst = *(byte*)pSrc; - *(short*)(pDst + 1) = *(short*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw4(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw5(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 1) = *(int*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw6(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 2) = *(int*)(pSrc + 2); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw7(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 3) = *(int*)(pSrc + 3); - } - - writer.Advance(src.Length); - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/UnsafeMemory.Low.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/UnsafeMemory.Low.cs.meta deleted file mode 100644 index 2e00993..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Internal/UnsafeMemory.Low.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ea00cefaa2f44ee408f3975719c372cb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4.meta deleted file mode 100644 index 496cb49..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 6879702e59bcf3d4db35a0eae88bb8e0 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Helper.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Helper.cs deleted file mode 100644 index 5c20043..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Helper.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { -#if UNITY_2018_3_OR_NEWER - - // use 'Safe' code for Unity because in IL2CPP gots strange behaviour. - - public static int Encode(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength) - { - if (IntPtr.Size == 4) - { - return LZ4Codec.Encode32Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - else - { - return LZ4Codec.Encode64Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - } - - public static int Decode(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength) - { - if (IntPtr.Size == 4) - { - return LZ4Codec.Decode32Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - else - { - return LZ4Codec.Decode64Safe(input, inputOffset, inputLength, output, outputOffset, outputLength); - } - } - -#endif - - internal static class HashTablePool - { - [ThreadStatic] - private static ushort[] ushortPool; - - [ThreadStatic] - private static uint[] uintPool; - - [ThreadStatic] - private static int[] intPool; - - public static ushort[] GetUShortHashTablePool() - { - if (ushortPool == null) - { - ushortPool = new ushort[HASH64K_TABLESIZE]; - } - else - { - Array.Clear(ushortPool, 0, ushortPool.Length); - } - - return ushortPool; - } - - public static uint[] GetUIntHashTablePool() - { - if (uintPool == null) - { - uintPool = new uint[HASH_TABLESIZE]; - } - else - { - Array.Clear(uintPool, 0, uintPool.Length); - } - - return uintPool; - } - - public static int[] GetIntHashTablePool() - { - if (intPool == null) - { - intPool = new int[HASH_TABLESIZE]; - } - else - { - Array.Clear(intPool, 0, intPool.Length); - } - - return intPool; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Helper.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Helper.cs.meta deleted file mode 100644 index 9080675..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Helper.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 135c503530b89854282de4c339084d74 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe.cs deleted file mode 100644 index 18e423a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe.cs +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if UNITY_2018_3_OR_NEWER - -#region license - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -using System; -using System.Diagnostics; - -namespace MessagePack.LZ4 -{ - /// Safe LZ4 codec. - internal partial class LZ4Codec - { -#region Helper - - [Conditional("DEBUG")] - private static void Assert(bool condition, string errorMessage) - { - if (!condition) - { - throw new ArgumentException(errorMessage); - } - - Debug.Assert(condition, errorMessage); - } - -#endregion - -#region Byte manipulation - - internal static void Poke2(byte[] buffer, int offset, ushort value) - { - buffer[offset] = (byte)value; - buffer[offset + 1] = (byte)(value >> 8); - } - - internal static ushort Peek2(byte[] buffer, int offset) - { - // NOTE: It's faster than BitConverter.ToUInt16 (suprised? me too) - return (ushort)(((uint)buffer[offset]) | ((uint)buffer[offset + 1] << 8)); - } - - internal static uint Peek4(byte[] buffer, int offset) - { - // NOTE: It's faster than BitConverter.ToUInt32 (suprised? me too) - return - ((uint)buffer[offset]) | - ((uint)buffer[offset + 1] << 8) | - ((uint)buffer[offset + 2] << 16) | - ((uint)buffer[offset + 3] << 24); - } - - private static uint Xor4(byte[] buffer, int offset1, int offset2) - { - // return Peek4(buffer, offset1) ^ Peek4(buffer, offset2); - var value1 = - ((uint)buffer[offset1]) | - ((uint)buffer[offset1 + 1] << 8) | - ((uint)buffer[offset1 + 2] << 16) | - ((uint)buffer[offset1 + 3] << 24); - var value2 = - ((uint)buffer[offset2]) | - ((uint)buffer[offset2 + 1] << 8) | - ((uint)buffer[offset2 + 2] << 16) | - ((uint)buffer[offset2 + 3] << 24); - return value1 ^ value2; - } - - private static ulong Xor8(byte[] buffer, int offset1, int offset2) - { - // return Peek8(buffer, offset1) ^ Peek8(buffer, offset2); - var value1 = - ((ulong)buffer[offset1]) | - ((ulong)buffer[offset1 + 1] << 8) | - ((ulong)buffer[offset1 + 2] << 16) | - ((ulong)buffer[offset1 + 3] << 24) | - ((ulong)buffer[offset1 + 4] << 32) | - ((ulong)buffer[offset1 + 5] << 40) | - ((ulong)buffer[offset1 + 6] << 48) | - ((ulong)buffer[offset1 + 7] << 56); - var value2 = - ((ulong)buffer[offset2]) | - ((ulong)buffer[offset2 + 1] << 8) | - ((ulong)buffer[offset2 + 2] << 16) | - ((ulong)buffer[offset2 + 3] << 24) | - ((ulong)buffer[offset2 + 4] << 32) | - ((ulong)buffer[offset2 + 5] << 40) | - ((ulong)buffer[offset2 + 6] << 48) | - ((ulong)buffer[offset2 + 7] << 56); - return value1 ^ value2; - } - - private static bool Equal2(byte[] buffer, int offset1, int offset2) - { - // return Peek2(buffer, offset1) == Peek2(buffer, offset2); - if (buffer[offset1] != buffer[offset2]) - { - return false; - } - - return buffer[offset1 + 1] == buffer[offset2 + 1]; - } - - private static bool Equal4(byte[] buffer, int offset1, int offset2) - { - // return Peek4(buffer, offset1) == Peek4(buffer, offset2); - if (buffer[offset1] != buffer[offset2]) - { - return false; - } - - if (buffer[offset1 + 1] != buffer[offset2 + 1]) - { - return false; - } - - if (buffer[offset1 + 2] != buffer[offset2 + 2]) - { - return false; - } - - return buffer[offset1 + 3] == buffer[offset2 + 3]; - } - -#endregion - -#region Byte block copy - - private static void Copy4(byte[] buf, int src, int dst) - { - Assert(dst > src, "Copying backwards is not implemented"); - buf[dst + 3] = buf[src + 3]; - buf[dst + 2] = buf[src + 2]; - buf[dst + 1] = buf[src + 1]; - buf[dst] = buf[src]; - } - - private static void Copy8(byte[] buf, int src, int dst) - { - Assert(dst > src, "Copying backwards is not implemented"); - buf[dst + 7] = buf[src + 7]; - buf[dst + 6] = buf[src + 6]; - buf[dst + 5] = buf[src + 5]; - buf[dst + 4] = buf[src + 4]; - buf[dst + 3] = buf[src + 3]; - buf[dst + 2] = buf[src + 2]; - buf[dst + 1] = buf[src + 1]; - buf[dst] = buf[src]; - } - - private static void BlockCopy(byte[] src, int src_0, byte[] dst, int dst_0, int len) - { - Assert(src != dst, "BlockCopy does not handle copying to the same buffer"); - - if (len >= BLOCK_COPY_LIMIT) - { - Buffer.BlockCopy(src, src_0, dst, dst_0, len); - } - else - { - while (len >= 8) - { - dst[dst_0] = src[src_0]; - dst[dst_0 + 1] = src[src_0 + 1]; - dst[dst_0 + 2] = src[src_0 + 2]; - dst[dst_0 + 3] = src[src_0 + 3]; - dst[dst_0 + 4] = src[src_0 + 4]; - dst[dst_0 + 5] = src[src_0 + 5]; - dst[dst_0 + 6] = src[src_0 + 6]; - dst[dst_0 + 7] = src[src_0 + 7]; - len -= 8; - src_0 += 8; - dst_0 += 8; - } - - while (len >= 4) - { - dst[dst_0] = src[src_0]; - dst[dst_0 + 1] = src[src_0 + 1]; - dst[dst_0 + 2] = src[src_0 + 2]; - dst[dst_0 + 3] = src[src_0 + 3]; - len -= 4; - src_0 += 4; - dst_0 += 4; - } - - while (len-- > 0) - { - dst[dst_0++] = src[src_0++]; - } - } - } - - private static int WildCopy(byte[] src, int src_0, byte[] dst, int dst_0, int dst_end) - { - var len = dst_end - dst_0; - - Assert(src != dst, "BlockCopy does not handle copying to the same buffer"); - Assert(len > 0, "Length have to be greater than 0"); - - if (len >= BLOCK_COPY_LIMIT) - { - Buffer.BlockCopy(src, src_0, dst, dst_0, len); - } - else - { - // apparently (tested) this is an overkill - // it seems to be faster without this 8-byte loop - ////while (len >= 8) - ////{ - //// dst[dst_0] = src[src_0]; - //// dst[dst_0 + 1] = src[src_0 + 1]; - //// dst[dst_0 + 2] = src[src_0 + 2]; - //// dst[dst_0 + 3] = src[src_0 + 3]; - //// dst[dst_0 + 4] = src[src_0 + 4]; - //// dst[dst_0 + 5] = src[src_0 + 5]; - //// dst[dst_0 + 6] = src[src_0 + 6]; - //// dst[dst_0 + 7] = src[src_0 + 7]; - //// len -= 8; src_0 += 8; dst_0 += 8; - ////} - - while (len >= 4) - { - dst[dst_0] = src[src_0]; - dst[dst_0 + 1] = src[src_0 + 1]; - dst[dst_0 + 2] = src[src_0 + 2]; - dst[dst_0 + 3] = src[src_0 + 3]; - len -= 4; - src_0 += 4; - dst_0 += 4; - } - - while (len-- > 0) - { - dst[dst_0++] = src[src_0++]; - } - } - - return len; - } - - private static int SecureCopy(byte[] buffer, int src, int dst, int dst_end) - { - var diff = dst - src; - var length = dst_end - dst; - var len = length; - - Assert(diff >= 4, "Target must be at least 4 bytes further than source"); - Assert(BLOCK_COPY_LIMIT > 4, "This method requires BLOCK_COPY_LIMIT > 4"); - Assert(len > 0, "Length have to be greater than 0"); - - if (diff >= BLOCK_COPY_LIMIT) - { - if (diff >= length) - { - Buffer.BlockCopy(buffer, src, buffer, dst, length); - return length; // done - } - - do - { - Buffer.BlockCopy(buffer, src, buffer, dst, diff); - src += diff; - dst += diff; - len -= diff; - } - while (len >= diff); - } - - // apparently (tested) this is an overkill - // it seems to be faster without this 8-byte loop - ////while (len >= 8) - ////{ - //// buffer[dst] = buffer[src]; - //// buffer[dst + 1] = buffer[src + 1]; - //// buffer[dst + 2] = buffer[src + 2]; - //// buffer[dst + 3] = buffer[src + 3]; - //// buffer[dst + 4] = buffer[src + 4]; - //// buffer[dst + 5] = buffer[src + 5]; - //// buffer[dst + 6] = buffer[src + 6]; - //// buffer[dst + 7] = buffer[src + 7]; - //// dst += 8; src += 8; len -= 8; - ////} - - while (len >= 4) - { - buffer[dst] = buffer[src]; - buffer[dst + 1] = buffer[src + 1]; - buffer[dst + 2] = buffer[src + 2]; - buffer[dst + 3] = buffer[src + 3]; - dst += 4; - src += 4; - len -= 4; - } - - while (len-- > 0) - { - buffer[dst++] = buffer[src++]; - } - - return length; // done - } - -#endregion - - /// Encodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Encode32Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - if (outputLength == 0) - { - return 0; - } - - if (inputLength < LZ4_64KLIMIT) - { - var hashTable = HashTablePool.GetUShortHashTablePool(); - return LZ4_compress64kCtx_safe32(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - else - { - var hashTable = HashTablePool.GetIntHashTablePool(); - return LZ4_compressCtx_safe32(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - } - - /// Encodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Encode64Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - if (outputLength == 0) - { - return 0; - } - - if (inputLength < LZ4_64KLIMIT) - { - var hashTable = HashTablePool.GetUShortHashTablePool(); - return LZ4_compress64kCtx_safe64(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - else - { - var hashTable = HashTablePool.GetIntHashTablePool(); - return LZ4_compressCtx_safe64(hashTable, input, output, inputOffset, outputOffset, inputLength, outputLength); - } - } - - /// Decodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Decode32Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - - if (outputLength == 0) - { - return 0; - } - - var length = LZ4_uncompress_safe32(input, output, inputOffset, outputOffset, outputLength); - if (length != inputLength) - { - throw new MessagePackSerializationException("LZ4 block is corrupted, or invalid length has been given."); - } - - return outputLength; - } - - /// Decodes the specified input. - /// The input. - /// The input offset. - /// Length of the input. - /// The output. - /// The output offset. - /// Length of the output. - /// Number of bytes written. - public static int Decode64Safe( - byte[] input, - int inputOffset, - int inputLength, - byte[] output, - int outputOffset, - int outputLength) - { - CheckArguments(input, inputOffset, inputLength, output, outputOffset, outputLength); - - if (outputLength == 0) - { - return 0; - } - - var length = LZ4_uncompress_safe64(input, output, inputOffset, outputOffset, outputLength); - if (length != inputLength) - { - throw new MessagePackSerializationException("LZ4 block is corrupted, or invalid length has been given."); - } - - return outputLength; - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe.cs.meta deleted file mode 100644 index 5f5e5b0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bfa77bfa8e74a914cada4663d406de46 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs deleted file mode 100644 index 0547213..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs +++ /dev/null @@ -1,753 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if UNITY_2018_3_OR_NEWER - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { -#region LZ4_compressCtx - - private static int LZ4_compressCtx_safe32( - int[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn32 = DEBRUIJN_TABLE_32; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_base = src_0; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST] = src_p - src_base; - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - } - while ((src_ref < src_p - MAX_DISTANCE) || (!Equal4(src, src_ref, src_p))); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (int)Xor4(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - src_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = src_p - src_anchor; - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - dst[dst_token] += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (length > 254) - { - length -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)length; - } - else - { - dst[dst_token] += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH_ADJUST] = src_p - 2 - src_base; - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - - if ((src_ref > src_p - (MAX_DISTANCE + 1)) && Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = src_end - src_anchor; - - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - } - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_compress64kCtx - - private static int LZ4_compress64kCtx_safe32( - ushort[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn32 = DEBRUIJN_TABLE_32; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while (!Equal4(src, src_ref, src_p)); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (int)Xor4(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - src_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = src_p - src_anchor; - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - dst[dst_token] += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (len > 254) - { - len -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)len; - } - else - { - dst[dst_token] += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if (Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - var lastRun = src_end - src_anchor; - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_uncompress - - private static int LZ4_uncompress_safe32( - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int dst_len) - { - unchecked - { - var dec32table = DECODER_TABLE_32; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - int dst_ref; - - var dst_p = dst_0; - var dst_end = dst_p + dst_len; - int dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_32 - 4); - - byte token; - - // Main Loop - while (true) - { - int length; - - // get runlength - token = src[src_p++]; - if ((length = token >> ML_BITS) == RUN_MASK) - { - int len; - for (; (len = src[src_p++]) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy(src, src_p, dst, dst_p, length); - src_p += length; - break; // EOF - } - - if (dst_p < dst_cpy) - { - _i = WildCopy(src, src_p, dst, dst_p, dst_cpy); - src_p += _i; - dst_p += _i; - } - - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - dst_ref = dst_cpy - Peek2(src, src_p); - src_p += 2; - if (dst_ref < dst_0) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = token & ML_MASK) == ML_MASK) - { - for (; src[src_p] == 255; length += 255) - { - src_p++; - } - - length += src[src_p++]; - } - - // copy repeated sequence - if ((dst_p - dst_ref) < STEPSIZE_32) - { - const int dec64 = 0; - dst[dst_p + 0] = dst[dst_ref + 0]; - dst[dst_p + 1] = dst[dst_ref + 1]; - dst[dst_p + 2] = dst[dst_ref + 2]; - dst[dst_p + 3] = dst[dst_ref + 3]; - dst_p += 4; - dst_ref += 4; - dst_ref -= dec32table[dst_p - dst_ref]; - Copy4(dst, dst_ref, dst_p); - dst_p += STEPSIZE_32 - 4; - dst_ref -= dec64; - } - else - { - Copy4(dst, dst_ref, dst_p); - dst_p += 4; - dst_ref += 4; - } - - dst_cpy = dst_p + length - (STEPSIZE_32 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - if (dst_p < dst_COPYLENGTH) - { - _i = SecureCopy(dst, dst_ref, dst_p, dst_COPYLENGTH); - dst_ref += _i; - dst_p += _i; - } - - while (dst_p < dst_cpy) - { - dst[dst_p++] = dst[dst_ref++]; - } - - dst_p = dst_cpy; - continue; - } - - if (dst_p < dst_cpy) - { - SecureCopy(dst, dst_ref, dst_p, dst_cpy); - } - - dst_p = dst_cpy; // correction - } - - // end of decoding - return src_p - src_0; - -// write overflow error detected -_output_error: - return -(src_p - src_0); - } - } - -#endregion - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs.meta deleted file mode 100644 index 0fb67a6..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe32.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e3af434f443715345a95c309036329e2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs deleted file mode 100644 index f8215f8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs +++ /dev/null @@ -1,774 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if UNITY_2018_3_OR_NEWER - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { -#region LZ4_compressCtx - - private static int LZ4_compressCtx_safe64( - int[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn64 = DEBRUIJN_TABLE_64; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_base = src_0; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST] = src_p - src_base; - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - } - while ((src_ref < src_p - MAX_DISTANCE) || (!Equal4(src, src_ref, src_p))); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (long)Xor8(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && Equal4(src, src_ref, src_p)) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = src_p - src_anchor; - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - dst[dst_token] += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (length > 254) - { - length -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)length; - } - else - { - dst[dst_token] += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH_ADJUST] = src_p - 2 - src_base; - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = src_p - src_base; - - if ((src_ref > src_p - (MAX_DISTANCE + 1)) && Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = src_end - src_anchor; - - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - } - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_compress64kCtx - - private static int LZ4_compress64kCtx_safe64( - ushort[] hash_table, - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int src_len, - int dst_maxlen) - { - unchecked - { - var debruijn64 = DEBRUIJN_TABLE_64; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst_0; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - int src_ref; - int dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (Peek4(src, src_p_fwd) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while (!Equal4(src, src_ref, src_p)); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src_0) && (src[src_p - 1] == src[src_ref - 1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = src_p - src_anchor; - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - dst[dst_token] = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - dst[dst_p++] = 255; - len -= 255; - } - while (len > 254); - dst[dst_p++] = (byte)len; - BlockCopy(src, src_anchor, dst, dst_p, length); - dst_p += length; - goto _next_match; - } - else - { - dst[dst_p++] = (byte)len; - } - } - else - { - dst[dst_token] = (byte)(length << ML_BITS); - } - - // Copy Literals - if (length > 0) - { - _i = dst_p + length; - WildCopy(src, src_anchor, dst, dst_p, _i); - dst_p = _i; - } - -_next_match: - -// Encode Offset - Poke2(dst, dst_p, (ushort)(src_p - src_ref)); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (long)Xor8(src, src_ref, src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && Equal4(src, src_ref, src_p)) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && Equal2(src, src_ref, src_p)) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (src[src_ref] == src[src_p])) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = src_p - src_anchor; - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - dst[dst_token] += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - dst[dst_p++] = 255; - dst[dst_p++] = 255; - } - - if (len > 254) - { - len -= 255; - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)len; - } - else - { - dst[dst_token] += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(Peek4(src, src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if (Equal4(src, src_ref, src_p)) - { - dst_token = dst_p++; - dst[dst_token] = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (Peek4(src, src_p) * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = src_end - src_anchor; - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - dst[dst_p++] = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - dst[dst_p++] = 255; - } - - dst[dst_p++] = (byte)lastRun; - } - else - { - dst[dst_p++] = (byte)(lastRun << ML_BITS); - } - - BlockCopy(src, src_anchor, dst, dst_p, src_end - src_anchor); - dst_p += src_end - src_anchor; - } - - // End - return dst_p - dst_0; - } - } - -#endregion - -#region LZ4_uncompress - - private static int LZ4_uncompress_safe64( - byte[] src, - byte[] dst, - int src_0, - int dst_0, - int dst_len) - { - unchecked - { - var dec32table = DECODER_TABLE_32; - var dec64table = DECODER_TABLE_64; - int _i; - - // ---- preprocessed source start here ---- - // r93 - var src_p = src_0; - int dst_ref; - - var dst_p = dst_0; - var dst_end = dst_p + dst_len; - int dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_64 - 4); - - uint token; - - // Main Loop - while (true) - { - int length; - - // get runlength - token = src[src_p++]; - if ((length = (byte)(token >> ML_BITS)) == RUN_MASK) - { - int len; - for (; (len = src[src_p++]) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy(src, src_p, dst, dst_p, length); - src_p += length; - break; // EOF - } - - if (dst_p < dst_cpy) - { - _i = WildCopy(src, src_p, dst, dst_p, dst_cpy); - src_p += _i; - dst_p += _i; - } - - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - dst_ref = dst_cpy - Peek2(src, src_p); - src_p += 2; - if (dst_ref < dst_0) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = (byte)(token & ML_MASK)) == ML_MASK) - { - for (; src[src_p] == 255; length += 255) - { - src_p++; - } - - length += src[src_p++]; - } - - // copy repeated sequence - if ((dst_p - dst_ref) < STEPSIZE_64) - { - var dec64 = dec64table[dst_p - dst_ref]; - - dst[dst_p + 0] = dst[dst_ref + 0]; - dst[dst_p + 1] = dst[dst_ref + 1]; - dst[dst_p + 2] = dst[dst_ref + 2]; - dst[dst_p + 3] = dst[dst_ref + 3]; - dst_p += 4; - dst_ref += 4; - dst_ref -= dec32table[dst_p - dst_ref]; - Copy4(dst, dst_ref, dst_p); - dst_p += STEPSIZE_64 - 4; - dst_ref -= dec64; - } - else - { - Copy8(dst, dst_ref, dst_p); - dst_p += 8; - dst_ref += 8; - } - - dst_cpy = dst_p + length - (STEPSIZE_64 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - if (dst_p < dst_COPYLENGTH) - { - _i = SecureCopy(dst, dst_ref, dst_p, dst_COPYLENGTH); - dst_ref += _i; - dst_p += _i; - } - - while (dst_p < dst_cpy) - { - dst[dst_p++] = dst[dst_ref++]; - } - - dst_p = dst_cpy; - continue; - } - - if (dst_p < dst_cpy) - { - SecureCopy(dst, dst_ref, dst_p, dst_cpy); - } - - dst_p = dst_cpy; // correction - } - - // end of decoding - return src_p - src_0; - -_output_error: - -// write overflow error detected - return -(src_p - src_0); - } - } - -#endregion - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs.meta deleted file mode 100644 index 3dda859..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Safe64.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2af5a6e86034ed44e91f32d31686d882 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe.cs deleted file mode 100644 index ec9a28b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region license - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -using System; - -namespace MessagePack.LZ4 -{ - /// Unsafe LZ4 codec. - internal partial class LZ4Codec - { - /// Encodes the specified input. - /// The input. - /// The output. - /// Number of bytes written. - public static unsafe int Encode(ReadOnlySpan input, Span output) - { - if (output.Length == 0) - { - throw new MessagePackSerializationException("Output is empty."); - } - - fixed (byte* inputPtr = input) - fixed (byte* outputPtr = output) - { - if (input.Length < LZ4_64KLIMIT) - { - var uHashTable = HashTablePool.GetUShortHashTablePool(); - fixed (ushort* hash1 = &uHashTable[0]) - { - if (IntPtr.Size == 4) - { - return LZ4_compress64kCtx_32(hash1, inputPtr, outputPtr, input.Length, output.Length); - } - else - { - return LZ4_compress64kCtx_64(hash1, inputPtr, outputPtr, input.Length, output.Length); - } - } - } - else - { - var bHashTable = HashTablePool.GetUIntHashTablePool(); - fixed (uint* hash2 = &bHashTable[0]) - { - if (IntPtr.Size == 4) - { - return LZ4_compressCtx_32(hash2, inputPtr, outputPtr, input.Length, output.Length); - } - else - { - return LZ4_compressCtx_64(hash2, inputPtr, outputPtr, input.Length, output.Length); - } - } - } - } - } - - /// Decodes the specified input. - /// The input. - /// The output. - /// Number of bytes written. - public static unsafe int Decode(ReadOnlySpan input, Span output) - { - if (output.Length == 0) - { - throw new MessagePackSerializationException("Output is empty."); - } - - fixed (byte* inputPtr = input) - fixed (byte* outputPtr = output) - { - int length; - if (IntPtr.Size == 4) - { - length = LZ4_uncompress_32(inputPtr, outputPtr, output.Length); - } - else - { - length = LZ4_uncompress_64(inputPtr, outputPtr, output.Length); - } - - if (length != input.Length) - { - throw new MessagePackSerializationException("LZ4 block is corrupted, or invalid length has been given."); - } - - return output.Length; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe.cs.meta deleted file mode 100644 index a730899..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3a48aac02d4c19049822a88ea40df7f5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs deleted file mode 100644 index 22d39b2..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs +++ /dev/null @@ -1,796 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { - #region LZ4_compressCtx_32 - - private static unsafe int LZ4_compressCtx_32( - uint* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - - fixed (int* debruijn32 = &DEBRUIJN_TABLE_32[0]) - { - // r93 - var src_p = src; - var src_base = src_p; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(*(uint*)src_p * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - src_base); - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* xxx_ref; - byte* xxx_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - } - while ((xxx_ref < src_p - MAX_DISTANCE) || ((*(uint*)xxx_ref) != (*(uint*)src_p))); - - // Catch up - while ((src_p > src_anchor) && (xxx_ref > src) && (src_p[-1] == xxx_ref[-1])) - { - src_p--; - xxx_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - xxx_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - *xxx_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy32(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *xxx_token = (byte)(length << ML_BITS); - } - - // Copy Literals - _p = dst_p + length; - do - { - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - } - while (dst_p < _p); - dst_p = _p; - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - xxx_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - xxx_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(int*)xxx_ref) ^ (*(int*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - xxx_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)xxx_ref) == (*(ushort*)src_p))) - { - src_p += 2; - xxx_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*xxx_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = (int)(src_p - src_anchor); - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - *xxx_token += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (length > 254) - { - length -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)length; - } - else - { - *xxx_token += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - - if ((xxx_ref > src_p - (MAX_DISTANCE + 1)) && ((*(uint*)xxx_ref) == (*(uint*)src_p))) - { - xxx_token = dst_p++; - *xxx_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = (int)(src_end - src_anchor); - - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy32(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - } - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_compress64kCtx_32 - - private static unsafe int LZ4_compress64kCtx_32( - ushort* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - fixed (int* debruijn32 = &DEBRUIJN_TABLE_32[0]) - { - // r93 - var src_p = src; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_32 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* xxx_ref; - byte* xxx_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH64K_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while ((*(uint*)xxx_ref) != (*(uint*)src_p)); - - // Catch up - while ((src_p > src_anchor) && (xxx_ref > src) && (src_p[-1] == xxx_ref[-1])) - { - src_p--; - xxx_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - xxx_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - *xxx_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy32(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *xxx_token = (byte)(length << ML_BITS); - } - - // Copy Literals - _p = dst_p + length; - do - { - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - *(uint*)dst_p = *(uint*)src_anchor; - dst_p += 4; - src_anchor += 4; - } - while (dst_p < _p); - dst_p = _p; - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - xxx_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - xxx_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(int*)xxx_ref) ^ (*(int*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_32; - xxx_ref += STEPSIZE_32; - continue; - } - - src_p += debruijn32[((uint)(diff & -diff) * 0x077CB531u) >> 27]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)xxx_ref) == (*(ushort*)src_p))) - { - src_p += 2; - xxx_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*xxx_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = (int)(src_p - src_anchor); - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - *xxx_token += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (len > 254) - { - len -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)len; - } - else - { - *xxx_token += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - xxx_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if ((*(uint*)xxx_ref) == (*(uint*)src_p)) - { - xxx_token = dst_p++; - *xxx_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - { - var lastRun = (int)(src_end - src_anchor); - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy32(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - } - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_uncompress_32 - - private static unsafe int LZ4_uncompress_32( - byte* src, - byte* dst, - int dst_len) - { - unchecked - { - fixed (int* dec32table = &DECODER_TABLE_32[0]) - { - // r93 - var src_p = src; - byte* xxx_ref; - - var dst_p = dst; - var dst_end = dst_p + dst_len; - byte* dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_32 - 4); - - uint xxx_token; - - // Main Loop - while (true) - { - int length; - - // get runlength - xxx_token = *src_p++; - if ((length = (int)(xxx_token >> ML_BITS)) == RUN_MASK) - { - int len; - for (; (len = *src_p++) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy32(src_p, dst_p, length); - src_p += length; - break; // EOF - } - - do - { - *(uint*)dst_p = *(uint*)src_p; - dst_p += 4; - src_p += 4; - *(uint*)dst_p = *(uint*)src_p; - dst_p += 4; - src_p += 4; - } - while (dst_p < dst_cpy); - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - xxx_ref = dst_cpy - (*(ushort*)src_p); - src_p += 2; - if (xxx_ref < dst) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = (int)(xxx_token & ML_MASK)) == ML_MASK) - { - for (; *src_p == 255; length += 255) - { - src_p++; - } - - length += *src_p++; - } - - // copy repeated sequence - if ((dst_p - xxx_ref) < STEPSIZE_32) - { - const int dec64 = 0; - - dst_p[0] = xxx_ref[0]; - dst_p[1] = xxx_ref[1]; - dst_p[2] = xxx_ref[2]; - dst_p[3] = xxx_ref[3]; - dst_p += 4; - xxx_ref += 4; - xxx_ref -= dec32table[dst_p - xxx_ref]; - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += STEPSIZE_32 - 4; - xxx_ref -= dec64; - } - else - { - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - } - - dst_cpy = dst_p + length - (STEPSIZE_32 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - { - do - { - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - } - while (dst_p < dst_COPYLENGTH); - } - - while (dst_p < dst_cpy) - { - *dst_p++ = *xxx_ref++; - } - - dst_p = dst_cpy; - continue; - } - - do - { - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - *(uint*)dst_p = *(uint*)xxx_ref; - dst_p += 4; - xxx_ref += 4; - } - while (dst_p < dst_cpy); - dst_p = dst_cpy; // correction - } - - // end of decoding - return (int)(src_p - src); - -// write overflow error detected -_output_error: - return (int)-(src_p - src); - } - } - } - - #endregion - - /// Copies block of memory. - /// The source. - /// The destination. - /// The length (in bytes). - private static unsafe void BlockCopy32(byte* src, byte* dst, int len) - { - while (len >= 4) - { - *(uint*)dst = *(uint*)src; - dst += 4; - src += 4; - len -= 4; - } - - if (len >= 2) - { - *(ushort*)dst = *(ushort*)src; - dst += 2; - src += 2; - len -= 2; - } - - if (len >= 1) - { - *dst = *src; /* d++; s++; l--; */ - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs.meta deleted file mode 100644 index 675fc7d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe32.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 70d519bda46ea2048bcde764d4f7088c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs deleted file mode 100644 index ba10e68..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs +++ /dev/null @@ -1,808 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region LZ4 original - -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2012, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html - - LZ4 source repository : http://code.google.com/p/lz4/ -*/ - -#endregion - -#region LZ4 port - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -#pragma warning disable SA1312 // Variable names should begin with lower-case letter - -namespace MessagePack.LZ4 -{ - internal partial class LZ4Codec - { - #region LZ4_compressCtx_64 - - private static unsafe int LZ4_compressCtx_64( - uint* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - - fixed (int* debruijn64 = &DEBRUIJN_TABLE_64[0]) - { - // r93 - var src_p = src; - var src_base = src_p; - var src_anchor = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int length; - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - hash_table[(*(uint*)src_p * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - src_base); - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* src_ref; - byte* dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - } - while ((src_ref < src_p - MAX_DISTANCE) || ((*(uint*)src_ref) != (*(uint*)src_p))); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src) && (src_p[-1] == src_ref[-1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - var len = length - RUN_MASK; - *dst_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy64(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *dst_token = (byte)(length << ML_BITS); - } - - // Copy Literals - _p = dst_p + length; - { - do - { - *(ulong*)dst_p = *(ulong*)src_anchor; - dst_p += 8; - src_anchor += 8; - } - while (dst_p < _p); - } - - dst_p = _p; - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - src_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch already verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(long*)src_ref) ^ (*(long*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && ((*(uint*)src_ref) == (*(uint*)src_p))) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)src_ref) == (*(ushort*)src_p))) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*src_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - length = (int)(src_p - src_anchor); - - if (dst_p + (length >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (length >= ML_MASK) - { - *dst_token += ML_MASK; - length -= ML_MASK; - for (; length > 509; length -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (length > 254) - { - length -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)length; - } - else - { - *dst_token += (byte)length; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH_ADJUST] = (uint)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (uint)(src_p - src_base); - - if ((src_ref > src_p - (MAX_DISTANCE + 1)) && ((*(uint*)src_ref) == (*(uint*)src_p))) - { - dst_token = dst_p++; - *dst_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH_ADJUST; - } - -_last_literals: - -// Encode Last Literals - var lastRun = (int)(src_end - src_anchor); - if (dst_p + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy64(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_compress64kCtx_64 - - private static unsafe int LZ4_compress64kCtx_64( - ushort* hash_table, - byte* src, - byte* dst, - int src_len, - int dst_maxlen) - { - unchecked - { - byte* _p; - - fixed (int* debruijn64 = &DEBRUIJN_TABLE_64[0]) - { - // r93 - var src_p = src; - var src_anchor = src_p; - var src_base = src_p; - var src_end = src_p + src_len; - var src_mflimit = src_end - MFLIMIT; - - var dst_p = dst; - var dst_end = dst_p + dst_maxlen; - - var src_LASTLITERALS = src_end - LASTLITERALS; - var src_LASTLITERALS_1 = src_LASTLITERALS - 1; - - var src_LASTLITERALS_3 = src_LASTLITERALS - 3; - - var src_LASTLITERALS_STEPSIZE_1 = src_LASTLITERALS - (STEPSIZE_64 - 1); - var dst_LASTLITERALS_1 = dst_end - (1 + LASTLITERALS); - var dst_LASTLITERALS_3 = dst_end - (2 + 1 + LASTLITERALS); - - int len, length; - - uint h, h_fwd; - - // Init - if (src_len < MINLENGTH) - { - goto _last_literals; - } - - // First Byte - src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - - // Main Loop - while (true) - { - var findMatchAttempts = (1 << SKIPSTRENGTH) + 3; - var src_p_fwd = src_p; - byte* src_ref; - byte* dst_token; - - // Find a match - do - { - h = h_fwd; - var step = findMatchAttempts++ >> SKIPSTRENGTH; - src_p = src_p_fwd; - src_p_fwd = src_p + step; - - if (src_p_fwd > src_mflimit) - { - goto _last_literals; - } - - h_fwd = (*(uint*)src_p_fwd * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - } - while ((*(uint*)src_ref) != (*(uint*)src_p)); - - // Catch up - while ((src_p > src_anchor) && (src_ref > src) && (src_p[-1] == src_ref[-1])) - { - src_p--; - src_ref--; - } - - // Encode Literal length - length = (int)(src_p - src_anchor); - dst_token = dst_p++; - - if (dst_p + length + (length >> 8) > dst_LASTLITERALS_3) - { - return 0; // Check output limit - } - - if (length >= RUN_MASK) - { - len = length - RUN_MASK; - *dst_token = RUN_MASK << ML_BITS; - if (len > 254) - { - do - { - *dst_p++ = 255; - len -= 255; - } - while (len > 254); - *dst_p++ = (byte)len; - BlockCopy64(src_anchor, dst_p, length); - dst_p += length; - goto _next_match; - } - - *dst_p++ = (byte)len; - } - else - { - *dst_token = (byte)(length << ML_BITS); - } - - // Copy Literals - { - _p = dst_p + length; - { - do - { - *(ulong*)dst_p = *(ulong*)src_anchor; - dst_p += 8; - src_anchor += 8; - } - while (dst_p < _p); - } - - dst_p = _p; - } - -_next_match: - -// Encode Offset - *(ushort*)dst_p = (ushort)(src_p - src_ref); - dst_p += 2; - - // Start Counting - src_p += MINMATCH; - src_ref += MINMATCH; // MinMatch verified - src_anchor = src_p; - - while (src_p < src_LASTLITERALS_STEPSIZE_1) - { - var diff = (*(long*)src_ref) ^ (*(long*)src_p); - if (diff == 0) - { - src_p += STEPSIZE_64; - src_ref += STEPSIZE_64; - continue; - } - - src_p += debruijn64[((ulong)(diff & -diff) * 0x0218A392CDABBD3FL) >> 58]; - goto _endCount; - } - - if ((src_p < src_LASTLITERALS_3) && ((*(uint*)src_ref) == (*(uint*)src_p))) - { - src_p += 4; - src_ref += 4; - } - - if ((src_p < src_LASTLITERALS_1) && ((*(ushort*)src_ref) == (*(ushort*)src_p))) - { - src_p += 2; - src_ref += 2; - } - - if ((src_p < src_LASTLITERALS) && (*src_ref == *src_p)) - { - src_p++; - } - -_endCount: - -// Encode MatchLength - len = (int)(src_p - src_anchor); - - if (dst_p + (len >> 8) > dst_LASTLITERALS_1) - { - return 0; // Check output limit - } - - if (len >= ML_MASK) - { - *dst_token += ML_MASK; - len -= ML_MASK; - for (; len > 509; len -= 510) - { - *dst_p++ = 255; - *dst_p++ = 255; - } - - if (len > 254) - { - len -= 255; - *dst_p++ = 255; - } - - *dst_p++ = (byte)len; - } - else - { - *dst_token += (byte)len; - } - - // Test end of chunk - if (src_p > src_mflimit) - { - src_anchor = src_p; - break; - } - - // Fill table - hash_table[(*(uint*)(src_p - 2) * 2654435761u) >> HASH64K_ADJUST] = (ushort)(src_p - 2 - src_base); - - // Test next position - h = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - src_ref = src_base + hash_table[h]; - hash_table[h] = (ushort)(src_p - src_base); - - if ((*(uint*)src_ref) == (*(uint*)src_p)) - { - dst_token = dst_p++; - *dst_token = 0; - goto _next_match; - } - - // Prepare next loop - src_anchor = src_p++; - h_fwd = (*(uint*)src_p * 2654435761u) >> HASH64K_ADJUST; - } - -_last_literals: - -// Encode Last Literals - var lastRun = (int)(src_end - src_anchor); - if (dst_p + lastRun + 1 + ((lastRun - RUN_MASK + 255) / 255) > dst_end) - { - return 0; - } - - if (lastRun >= RUN_MASK) - { - *dst_p++ = RUN_MASK << ML_BITS; - lastRun -= RUN_MASK; - for (; lastRun > 254; lastRun -= 255) - { - *dst_p++ = 255; - } - - *dst_p++ = (byte)lastRun; - } - else - { - *dst_p++ = (byte)(lastRun << ML_BITS); - } - - BlockCopy64(src_anchor, dst_p, (int)(src_end - src_anchor)); - dst_p += src_end - src_anchor; - - // End - return (int)(dst_p - dst); - } - } - } - - #endregion - - #region LZ4_uncompress_64 - - private static unsafe int LZ4_uncompress_64( - byte* src, - byte* dst, - int dst_len) - { - unchecked - { - fixed (int* dec32table = &DECODER_TABLE_32[0]) - fixed (int* dec64table = &DECODER_TABLE_64[0]) - { - // r93 - var src_p = src; - byte* dst_ref; - - var dst_p = dst; - var dst_end = dst_p + dst_len; - byte* dst_cpy; - - var dst_LASTLITERALS = dst_end - LASTLITERALS; - var dst_COPYLENGTH = dst_end - COPYLENGTH; - var dst_COPYLENGTH_STEPSIZE_4 = dst_end - COPYLENGTH - (STEPSIZE_64 - 4); - - byte token; - - // Main Loop - while (true) - { - int length; - - // get runlength - token = *src_p++; - if ((length = token >> ML_BITS) == RUN_MASK) - { - int len; - for (; (len = *src_p++) == 255; length += 255) - { - /* do nothing */ - } - - length += len; - } - - // copy literals - dst_cpy = dst_p + length; - - if (dst_cpy > dst_COPYLENGTH) - { - if (dst_cpy != dst_end) - { - goto _output_error; // Error : not enough place for another match (min 4) + 5 literals - } - - BlockCopy64(src_p, dst_p, length); - src_p += length; - break; // EOF - } - - do - { - *(ulong*)dst_p = *(ulong*)src_p; - dst_p += 8; - src_p += 8; - } - while (dst_p < dst_cpy); - src_p -= dst_p - dst_cpy; - dst_p = dst_cpy; - - // get offset - dst_ref = dst_cpy - (*(ushort*)src_p); - src_p += 2; - if (dst_ref < dst) - { - goto _output_error; // Error : offset outside destination buffer - } - - // get matchlength - if ((length = token & ML_MASK) == ML_MASK) - { - for (; *src_p == 255; length += 255) - { - src_p++; - } - - length += *src_p++; - } - - // copy repeated sequence - if ((dst_p - dst_ref) < STEPSIZE_64) - { - var dec64 = dec64table[dst_p - dst_ref]; - - dst_p[0] = dst_ref[0]; - dst_p[1] = dst_ref[1]; - dst_p[2] = dst_ref[2]; - dst_p[3] = dst_ref[3]; - dst_p += 4; - dst_ref += 4; - dst_ref -= dec32table[dst_p - dst_ref]; - *(uint*)dst_p = *(uint*)dst_ref; - dst_p += STEPSIZE_64 - 4; - dst_ref -= dec64; - } - else - { - *(ulong*)dst_p = *(ulong*)dst_ref; - dst_p += 8; - dst_ref += 8; - } - - dst_cpy = dst_p + length - (STEPSIZE_64 - 4); - - if (dst_cpy > dst_COPYLENGTH_STEPSIZE_4) - { - if (dst_cpy > dst_LASTLITERALS) - { - goto _output_error; // Error : last 5 bytes must be literals - } - - while (dst_p < dst_COPYLENGTH) - { - *(ulong*)dst_p = *(ulong*)dst_ref; - dst_p += 8; - dst_ref += 8; - } - - while (dst_p < dst_cpy) - { - *dst_p++ = *dst_ref++; - } - - dst_p = dst_cpy; - continue; - } - - { - do - { - *(ulong*)dst_p = *(ulong*)dst_ref; - dst_p += 8; - dst_ref += 8; - } - while (dst_p < dst_cpy); - } - - dst_p = dst_cpy; // correction - } - - // end of decoding - return (int)(src_p - src); - -// write overflow error detected -_output_error: - return (int)-(src_p - src); - } - } - } - - #endregion - - /// Copies block of memory. - /// The source. - /// The destination. - /// The length (in bytes). - private static unsafe void BlockCopy64(byte* src, byte* dst, int len) - { - while (len >= 8) - { - *(ulong*)dst = *(ulong*)src; - dst += 8; - src += 8; - len -= 8; - } - - if (len >= 4) - { - *(uint*)dst = *(uint*)src; - dst += 4; - src += 4; - len -= 4; - } - - if (len >= 2) - { - *(ushort*)dst = *(ushort*)src; - dst += 2; - src += 2; - len -= 2; - } - - if (len >= 1) - { - *dst = *src; /* d++; s++; l--; */ - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs.meta deleted file mode 100644 index 581d1a0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.Unsafe64.Dirty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5dd9161b1f56b464a8db9b3d96dca169 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.cs deleted file mode 100644 index 8445807..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#region license - -/* -Copyright (c) 2013, Milosz Krajewski -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided -that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions - and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions - and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#endregion - -using System; - -#pragma warning disable SA1310 // Field names should not contain underscore - -namespace MessagePack.LZ4 -{ - internal static partial class LZ4Codec - { - #region configuration - - /// - /// Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - /// Increasing memory usage improves compression ratio - /// Reduced memory usage can improve speed, due to cache effect - /// Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache. - /// - private const int MEMORY_USAGE = 12; // modified use 12. - - /// - /// Decreasing this value will make the algorithm skip faster data segments considered "incompressible" - /// This may decrease compression ratio dramatically, but will be faster on incompressible data - /// Increasing this value will make the algorithm search more before declaring a segment "incompressible" - /// This could improve compression a bit, but will be slower on incompressible data - /// The default value (6) is recommended. - /// - private const int NOTCOMPRESSIBLE_DETECTIONLEVEL = 6; - - #endregion - - #region consts - - private const int MINMATCH = 4; - -#pragma warning disable 162, 429 - - private const int SKIPSTRENGTH = NOTCOMPRESSIBLE_DETECTIONLEVEL > 2 ? NOTCOMPRESSIBLE_DETECTIONLEVEL : 2; -#pragma warning restore 162, 429 - - private const int COPYLENGTH = 8; - private const int LASTLITERALS = 5; - private const int MFLIMIT = COPYLENGTH + MINMATCH; - private const int MINLENGTH = MFLIMIT + 1; - private const int MAXD_LOG = 16; - private const int MAXD = 1 << MAXD_LOG; - private const int MAXD_MASK = MAXD - 1; - private const int MAX_DISTANCE = (1 << MAXD_LOG) - 1; - private const int ML_BITS = 4; - private const int ML_MASK = (1 << ML_BITS) - 1; - private const int RUN_BITS = 8 - ML_BITS; - private const int RUN_MASK = (1 << RUN_BITS) - 1; - private const int STEPSIZE_64 = 8; - private const int STEPSIZE_32 = 4; - - private const int LZ4_64KLIMIT = (1 << 16) + (MFLIMIT - 1); - - private const int HASH_LOG = MEMORY_USAGE - 2; - private const int HASH_TABLESIZE = 1 << HASH_LOG; - private const int HASH_ADJUST = (MINMATCH * 8) - HASH_LOG; - - private const int HASH64K_LOG = HASH_LOG + 1; - private const int HASH64K_TABLESIZE = 1 << HASH64K_LOG; - private const int HASH64K_ADJUST = (MINMATCH * 8) - HASH64K_LOG; - - private const int HASHHC_LOG = MAXD_LOG - 1; - private const int HASHHC_TABLESIZE = 1 << HASHHC_LOG; - private const int HASHHC_ADJUST = (MINMATCH * 8) - HASHHC_LOG; - ////private const int HASHHC_MASK = HASHHC_TABLESIZE - 1; - - private const int MAX_NB_ATTEMPTS = 256; - private const int OPTIMAL_ML = ML_MASK - 1 + MINMATCH; - - private const int BLOCK_COPY_LIMIT = 16; - - private static readonly int[] DECODER_TABLE_32 = { 0, 3, 2, 3, 0, 0, 0, 0 }; - private static readonly int[] DECODER_TABLE_64 = { 0, 0, 0, -1, 0, 1, 2, 3 }; - - private static readonly int[] DEBRUIJN_TABLE_32 = - { - 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, - 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1, - }; - - private static readonly int[] DEBRUIJN_TABLE_64 = - { - 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, - 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, - 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, - 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7, - }; - - #endregion - - #region public interface (common) - - /// Gets maximum the length of the output. - /// Length of the input. - /// Maximum number of bytes needed for compressed buffer. - public static int MaximumOutputLength(int inputLength) - { - return inputLength + (inputLength / 255) + 16; - } - - #endregion - - #region internal interface (common) - - internal static void CheckArguments(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength) - { - if (inputLength == 0) - { - outputLength = 0; - return; - } - - if (input == null) - { - throw new ArgumentNullException("input"); - } - - if ((uint)inputOffset > (uint)input.Length) - { - throw new ArgumentOutOfRangeException("inputOffset"); - } - - if ((uint)inputLength > (uint)input.Length - (uint)inputOffset) - { - throw new ArgumentOutOfRangeException("inputLength"); - } - - if (output == null) - { - throw new ArgumentNullException("output"); - } - - if ((uint)outputOffset > (uint)output.Length) - { - throw new ArgumentOutOfRangeException("outputOffset"); - } - - if ((uint)outputLength > (uint)output.Length - (uint)outputOffset) - { - throw new ArgumentOutOfRangeException("outputLength"); - } - } - - #endregion - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.cs.meta deleted file mode 100644 index 3c0159c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/LZ4/LZ4Codec.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 467a42ca49e959542b69efdf5b046249 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePack.asmdef b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePack.asmdef deleted file mode 100644 index f1e851e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePack.asmdef +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "MessagePack", - "references": [ - "MessagePack.Annotations" - ], - "optionalUnityReferences": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": true, - "overrideReferences": true, - "precompiledReferences": [ - "System.Memory.dll", - "System.Buffers.dll", - "System.Threading.Tasks.Extensions.dll", - "System.Runtime.CompilerServices.Unsafe.dll", - "System.Runtime.Extensions.dll" - ], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [] -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePack.asmdef.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePack.asmdef.meta deleted file mode 100644 index c40ca3e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePack.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: bbde805d927e795439d7a746d1749cab -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCode.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCode.cs deleted file mode 100644 index 2537479..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCode.cs +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Text; - -namespace MessagePack -{ - /// - /// https://github.com/msgpack/msgpack/blob/master/spec.md#serialization-type-to-format-conversion. - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - enum MessagePackType : byte - { - Unknown = 0, - - Integer = 1, - Nil = 2, - Boolean = 3, - Float = 4, - String = 5, - Binary = 6, - Array = 7, - Map = 8, - Extension = 9, - } - - /// - /// The core type codes as defined by msgpack. - /// - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - static class MessagePackCode - { - public const byte MinFixInt = 0x00; // 0 - public const byte MaxFixInt = 0x7f; // 127 - public const byte MinFixMap = 0x80; // 128 - public const byte MaxFixMap = 0x8f; // 143 - public const byte MinFixArray = 0x90; // 144 - public const byte MaxFixArray = 0x9f; // 159 - public const byte MinFixStr = 0xa0; // 160 - public const byte MaxFixStr = 0xbf; // 191 - public const byte Nil = 0xc0; - public const byte NeverUsed = 0xc1; - public const byte False = 0xc2; - public const byte True = 0xc3; - public const byte Bin8 = 0xc4; - public const byte Bin16 = 0xc5; - public const byte Bin32 = 0xc6; - public const byte Ext8 = 0xc7; - public const byte Ext16 = 0xc8; - public const byte Ext32 = 0xc9; - public const byte Float32 = 0xca; - public const byte Float64 = 0xcb; - public const byte UInt8 = 0xcc; - public const byte UInt16 = 0xcd; - public const byte UInt32 = 0xce; - public const byte UInt64 = 0xcf; - public const byte Int8 = 0xd0; - public const byte Int16 = 0xd1; - public const byte Int32 = 0xd2; - public const byte Int64 = 0xd3; - public const byte FixExt1 = 0xd4; - public const byte FixExt2 = 0xd5; - public const byte FixExt4 = 0xd6; - public const byte FixExt8 = 0xd7; - public const byte FixExt16 = 0xd8; - public const byte Str8 = 0xd9; - public const byte Str16 = 0xda; - public const byte Str32 = 0xdb; - public const byte Array16 = 0xdc; - public const byte Array32 = 0xdd; - public const byte Map16 = 0xde; - public const byte Map32 = 0xdf; - public const byte MinNegativeFixInt = 0xe0; // 224 - public const byte MaxNegativeFixInt = 0xff; // 255 - - private static readonly MessagePackType[] TypeLookupTable = new MessagePackType[256]; - private static readonly string[] FormatNameTable = new string[256]; - - static MessagePackCode() - { - // Init Lookup Table - for (int i = MinFixInt; i <= MaxFixInt; i++) - { - TypeLookupTable[i] = MessagePackType.Integer; - FormatNameTable[i] = "positive fixint"; - } - - for (int i = MinFixMap; i <= MaxFixMap; i++) - { - TypeLookupTable[i] = MessagePackType.Map; - FormatNameTable[i] = "fixmap"; - } - - for (int i = MinFixArray; i <= MaxFixArray; i++) - { - TypeLookupTable[i] = MessagePackType.Array; - FormatNameTable[i] = "fixarray"; - } - - for (int i = MinFixStr; i <= MaxFixStr; i++) - { - TypeLookupTable[i] = MessagePackType.String; - FormatNameTable[i] = "fixstr"; - } - - TypeLookupTable[Nil] = MessagePackType.Nil; - TypeLookupTable[NeverUsed] = MessagePackType.Unknown; - TypeLookupTable[False] = MessagePackType.Boolean; - TypeLookupTable[True] = MessagePackType.Boolean; - TypeLookupTable[Bin8] = MessagePackType.Binary; - TypeLookupTable[Bin16] = MessagePackType.Binary; - TypeLookupTable[Bin32] = MessagePackType.Binary; - TypeLookupTable[Ext8] = MessagePackType.Extension; - TypeLookupTable[Ext16] = MessagePackType.Extension; - TypeLookupTable[Ext32] = MessagePackType.Extension; - TypeLookupTable[Float32] = MessagePackType.Float; - TypeLookupTable[Float64] = MessagePackType.Float; - TypeLookupTable[UInt8] = MessagePackType.Integer; - TypeLookupTable[UInt16] = MessagePackType.Integer; - TypeLookupTable[UInt32] = MessagePackType.Integer; - TypeLookupTable[UInt64] = MessagePackType.Integer; - TypeLookupTable[Int8] = MessagePackType.Integer; - TypeLookupTable[Int16] = MessagePackType.Integer; - TypeLookupTable[Int32] = MessagePackType.Integer; - TypeLookupTable[Int64] = MessagePackType.Integer; - TypeLookupTable[FixExt1] = MessagePackType.Extension; - TypeLookupTable[FixExt2] = MessagePackType.Extension; - TypeLookupTable[FixExt4] = MessagePackType.Extension; - TypeLookupTable[FixExt8] = MessagePackType.Extension; - TypeLookupTable[FixExt16] = MessagePackType.Extension; - TypeLookupTable[Str8] = MessagePackType.String; - TypeLookupTable[Str16] = MessagePackType.String; - TypeLookupTable[Str32] = MessagePackType.String; - TypeLookupTable[Array16] = MessagePackType.Array; - TypeLookupTable[Array32] = MessagePackType.Array; - TypeLookupTable[Map16] = MessagePackType.Map; - TypeLookupTable[Map32] = MessagePackType.Map; - - FormatNameTable[Nil] = "nil"; - FormatNameTable[NeverUsed] = "(never used)"; - FormatNameTable[False] = "false"; - FormatNameTable[True] = "true"; - FormatNameTable[Bin8] = "bin 8"; - FormatNameTable[Bin16] = "bin 16"; - FormatNameTable[Bin32] = "bin 32"; - FormatNameTable[Ext8] = "ext 8"; - FormatNameTable[Ext16] = "ext 16"; - FormatNameTable[Ext32] = "ext 32"; - FormatNameTable[Float32] = "float 32"; - FormatNameTable[Float64] = "float 64"; - FormatNameTable[UInt8] = "uint 8"; - FormatNameTable[UInt16] = "uint 16"; - FormatNameTable[UInt32] = "uint 32"; - FormatNameTable[UInt64] = "uint 64"; - FormatNameTable[Int8] = "int 8"; - FormatNameTable[Int16] = "int 16"; - FormatNameTable[Int32] = "int 32"; - FormatNameTable[Int64] = "int 64"; - FormatNameTable[FixExt1] = "fixext 1"; - FormatNameTable[FixExt2] = "fixext 2"; - FormatNameTable[FixExt4] = "fixext 4"; - FormatNameTable[FixExt8] = "fixext 8"; - FormatNameTable[FixExt16] = "fixext 16"; - FormatNameTable[Str8] = "str 8"; - FormatNameTable[Str16] = "str 16"; - FormatNameTable[Str32] = "str 32"; - FormatNameTable[Array16] = "array 16"; - FormatNameTable[Array32] = "array 32"; - FormatNameTable[Map16] = "map 16"; - FormatNameTable[Map32] = "map 32"; - - for (int i = MinNegativeFixInt; i <= MaxNegativeFixInt; i++) - { - TypeLookupTable[i] = MessagePackType.Integer; - FormatNameTable[i] = "negative fixint"; - } - } - - public static MessagePackType ToMessagePackType(byte code) - { - return TypeLookupTable[code]; - } - - public static string ToFormatName(byte code) - { - return FormatNameTable[code]; - } - - /// - /// Checks whether a given messagepack code represents an integer that might include a sign (i.e. might be a negative number). - /// - /// The messagepack code. - /// A boolean value. - internal static bool IsSignedInteger(byte code) - { - switch (code) - { - case Int8: - case Int16: - case Int32: - case Int64: - return true; - default: - return code >= MinNegativeFixInt && code <= MaxNegativeFixInt; - } - } - } - - /// - /// The officially defined messagepack extension type codes. - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - static class ReservedMessagePackExtensionTypeCode - { - public const sbyte DateTime = -1; - } - -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - static class MessagePackRange - { - public const int MinFixNegativeInt = -32; - public const int MaxFixNegativeInt = -1; - public const int MaxFixPositiveInt = 127; - public const int MinFixStringLength = 0; - public const int MaxFixStringLength = 31; - public const int MaxFixMapCount = 15; - public const int MaxFixArrayCount = 15; - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCode.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCode.cs.meta deleted file mode 100644 index f329627..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCode.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5abed96afe37b3c4e8d58b04054129c5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCompression.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCompression.cs deleted file mode 100644 index 1fb1a72..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCompression.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack -{ - /// - /// Identifies the various compression schemes which might be applied at the msgpack level. - /// - public enum MessagePackCompression - { - /// - /// No compression is applied at the msgpack level. - /// - None, - - /// - /// Compresses an entire msgpack sequence as a single lz4 block format. - /// This is the simple compression that achieves best compression ratio, - /// at the cost of copying the entire sequence when necessary to get contiguous memory. - /// - /// - /// Uses msgpack type code ext99 and is compatible with v1 of this library. - /// - /// - /// See also ThisLibraryExtensionTypeCodes.Lz4Block - /// - Lz4Block, - - /// - /// Compresses an entire msgpack sequence as a array of lz4 block format. - /// This is compressed/decompressed in chunks that do not consume LOH, - /// but the compression ratio is slightly sacrificed. - /// - /// - /// Uses msgpack type code ext98 in array. - /// - /// - /// See also ThisLibraryExtensionTypeCodes.Lz4BlockArray - /// - Lz4BlockArray, - } - -#pragma warning disable SA1649 // File name should match first type name - - /// - /// Extensions for . - /// - internal static class MessagePackCompressionExtensions - { - public static bool IsCompression(this MessagePackCompression compression) - { - return compression != MessagePackCompression.None; - } - } - -#pragma warning restore SA1649 // File name should match first type name -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCompression.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCompression.cs.meta deleted file mode 100644 index 3538ce1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackCompression.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 726b009260cea9e45a7c8541e288ca31 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackReader.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackReader.cs deleted file mode 100644 index e8a01fd..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackReader.cs +++ /dev/null @@ -1,1149 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Diagnostics; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading; -using MessagePack.Internal; - -namespace MessagePack -{ - /// - /// A primitive types reader for the MessagePack format. - /// - /// - /// The MessagePack spec.. - /// - /// Thrown when reading methods fail due to invalid data. - /// Thrown by reading methods when there are not enough bytes to read the required value. -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - ref partial struct MessagePackReader - { - /// - /// The reader over the sequence. - /// - private SequenceReader reader; - - /// - /// Initializes a new instance of the struct. - /// - /// The buffer to read from. - public MessagePackReader(ReadOnlyMemory memory) - : this() - { - this.reader = new SequenceReader(memory); - this.Depth = 0; - } - - /// - /// Initializes a new instance of the struct. - /// - /// The sequence to read from. - public MessagePackReader(in ReadOnlySequence readOnlySequence) - : this() - { - this.reader = new SequenceReader(readOnlySequence); - this.Depth = 0; - } - - /// - /// Gets or sets the cancellation token for this deserialization operation. - /// - public CancellationToken CancellationToken { get; set; } - - /// - /// Gets or sets the present depth of the object graph being deserialized. - /// - public int Depth { get; set; } - - /// - /// Gets the originally supplied to the constructor. - /// - public ReadOnlySequence Sequence => this.reader.Sequence; - - /// - /// Gets the current position of the reader within . - /// - public SequencePosition Position => this.reader.Position; - - /// - /// Gets the number of bytes consumed by the reader. - /// - public long Consumed => this.reader.Consumed; - - /// - /// Gets a value indicating whether the reader is at the end of the sequence. - /// - public bool End => this.reader.End; - - /// - /// Gets a value indicating whether the reader position is pointing at a nil value. - /// - /// Thrown if the end of the sequence provided to the constructor is reached before the expected end of the data. - public bool IsNil => this.NextCode == MessagePackCode.Nil; - - /// - /// Gets the next message pack type to be read. - /// - public MessagePackType NextMessagePackType => MessagePackCode.ToMessagePackType(this.NextCode); - - /// - /// Gets the type of the next MessagePack block. - /// - /// Thrown if the end of the sequence provided to the constructor is reached before the expected end of the data. - /// - /// See for valid message pack codes and ranges. - /// - public byte NextCode - { - get - { - ThrowInsufficientBufferUnless(this.reader.TryPeek(out byte code)); - return code; - } - } - - /// - /// Initializes a new instance of the struct, - /// with the same settings as this one, but with its own buffer to read from. - /// - /// The sequence to read from. - /// The new reader. - public MessagePackReader Clone(in ReadOnlySequence readOnlySequence) => new MessagePackReader(readOnlySequence) - { - CancellationToken = this.CancellationToken, - Depth = this.Depth, - }; - - /// - /// Creates a new at this reader's current position. - /// The two readers may then be used independently without impacting each other. - /// - /// A new . - /// - /// Since this is a struct, copying it completely is as simple as returning itself - /// from a property that isn't a "ref return" property. - /// - public MessagePackReader CreatePeekReader() => this; - - /// - /// Advances the reader to the next MessagePack primitive to be read. - /// - /// - /// The entire primitive is skipped, including content of maps or arrays, or any other type with payloads. - /// To get the raw MessagePack sequence that was skipped, use instead. - /// - public void Skip() => ThrowInsufficientBufferUnless(this.TrySkip()); - - /// - /// Advances the reader to the next MessagePack primitive to be read. - /// - /// true if the entire structure beginning at the current is found in the ; false otherwise. - /// - /// The entire primitive is skipped, including content of maps or arrays, or any other type with payloads. - /// To get the raw MessagePack sequence that was skipped, use instead. - /// WARNING: when false is returned, the position of the reader is undefined. - /// - internal bool TrySkip() - { - if (this.reader.Remaining == 0) - { - return false; - } - - byte code = this.NextCode; - switch (code) - { - case MessagePackCode.Nil: - case MessagePackCode.True: - case MessagePackCode.False: - return this.reader.TryAdvance(1); - case MessagePackCode.Int8: - case MessagePackCode.UInt8: - return this.reader.TryAdvance(2); - case MessagePackCode.Int16: - case MessagePackCode.UInt16: - return this.reader.TryAdvance(3); - case MessagePackCode.Int32: - case MessagePackCode.UInt32: - case MessagePackCode.Float32: - return this.reader.TryAdvance(5); - case MessagePackCode.Int64: - case MessagePackCode.UInt64: - case MessagePackCode.Float64: - return this.reader.TryAdvance(9); - case MessagePackCode.Map16: - case MessagePackCode.Map32: - return this.TrySkipNextMap(); - case MessagePackCode.Array16: - case MessagePackCode.Array32: - return this.TrySkipNextArray(); - case MessagePackCode.Str8: - case MessagePackCode.Str16: - case MessagePackCode.Str32: - return this.TryGetStringLengthInBytes(out int length) && this.reader.TryAdvance(length); - case MessagePackCode.Bin8: - case MessagePackCode.Bin16: - case MessagePackCode.Bin32: - return this.TryGetBytesLength(out length) && this.reader.TryAdvance(length); - case MessagePackCode.FixExt1: - case MessagePackCode.FixExt2: - case MessagePackCode.FixExt4: - case MessagePackCode.FixExt8: - case MessagePackCode.FixExt16: - case MessagePackCode.Ext8: - case MessagePackCode.Ext16: - case MessagePackCode.Ext32: - return this.TryReadExtensionFormatHeader(out ExtensionHeader header) && this.reader.TryAdvance(header.Length); - default: - if ((code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) || - (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt)) - { - return this.reader.TryAdvance(1); - } - - if (code >= MessagePackCode.MinFixMap && code <= MessagePackCode.MaxFixMap) - { - return this.TrySkipNextMap(); - } - - if (code >= MessagePackCode.MinFixArray && code <= MessagePackCode.MaxFixArray) - { - return this.TrySkipNextArray(); - } - - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - return this.TryGetStringLengthInBytes(out length) && this.reader.TryAdvance(length); - } - - // We don't actually expect to ever hit this point, since every code is supported. - Debug.Fail("Missing handler for code: " + code); - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a value. - /// - /// A nil value. - public Nil ReadNil() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - return code == MessagePackCode.Nil - ? Nil.Default - : throw ThrowInvalidCode(code); - } - - /// - /// Reads nil if it is the next token. - /// - /// true if the next token was nil; false otherwise. - /// Thrown if the end of the sequence provided to the constructor is reached before the expected end of the data. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryReadNil() - { - if (this.NextCode == MessagePackCode.Nil) - { - this.reader.Advance(1); - return true; - } - - return false; - } - - /// - /// Reads a sequence of bytes without any decoding. - /// - /// The number of bytes to read. - /// The sequence of bytes read. - public ReadOnlySequence ReadRaw(long length) - { - try - { - ReadOnlySequence result = this.reader.Sequence.Slice(this.reader.Position, length); - this.reader.Advance(length); - return result; - } - catch (ArgumentOutOfRangeException ex) - { - throw ThrowNotEnoughBytesException(ex); - } - } - - /// - /// Reads the next MessagePack primitive. - /// - /// The raw MessagePack sequence. - /// - /// The entire primitive is read, including content of maps or arrays, or any other type with payloads. - /// - public ReadOnlySequence ReadRaw() - { - SequencePosition initialPosition = this.Position; - this.Skip(); - return this.Sequence.Slice(initialPosition, this.Position); - } - - /// - /// Read an array header from - /// , - /// , or - /// some built-in code between and . - /// - /// - /// Thrown if the header cannot be read in the bytes left in the - /// or if it is clear that there are insufficient bytes remaining after the header to include all the elements the header claims to be there. - /// - /// Thrown if a code other than an array header is encountered. - public int ReadArrayHeader() - { - ThrowInsufficientBufferUnless(this.TryReadArrayHeader(out int count)); - - // Protect against corrupted or mischievious data that may lead to allocating way too much memory. - // We allow for each primitive to be the minimal 1 byte in size. - // Formatters that know each element is larger can optionally add a stronger check. - ThrowInsufficientBufferUnless(this.reader.Remaining >= count); - - return count; - } - - /// - /// Reads an array header from - /// , - /// , or - /// some built-in code between and - /// if there is sufficient buffer to read it. - /// - /// Receives the number of elements in the array if the entire array header could be read. - /// true if there was sufficient buffer and an array header was found; false if the buffer incompletely describes an array header. - /// Thrown if a code other than an array header is encountered. - /// - /// When this method returns false the position of the reader is left in an undefined position. - /// The caller is expected to recreate the reader (presumably with a longer sequence to read from) before continuing. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryReadArrayHeader(out int count) - { - count = -1; - if (!this.reader.TryRead(out byte code)) - { - return false; - } - - switch (code) - { - case MessagePackCode.Array16: - if (!this.reader.TryReadBigEndian(out short shortValue)) - { - return false; - } - - count = unchecked((ushort)shortValue); - break; - case MessagePackCode.Array32: - if (!this.reader.TryReadBigEndian(out int intValue)) - { - return false; - } - - count = intValue; - break; - default: - if (code >= MessagePackCode.MinFixArray && code <= MessagePackCode.MaxFixArray) - { - count = code & 0xF; - break; - } - - throw ThrowInvalidCode(code); - } - - return true; - } - - /// - /// Read a map header from - /// , - /// , or - /// some built-in code between and . - /// - /// The number of key=value pairs in the map. - /// - /// Thrown if the header cannot be read in the bytes left in the - /// or if it is clear that there are insufficient bytes remaining after the header to include all the elements the header claims to be there. - /// - /// Thrown if a code other than an map header is encountered. - public int ReadMapHeader() - { - ThrowInsufficientBufferUnless(this.TryReadMapHeader(out int count)); - - // Protect against corrupted or mischievious data that may lead to allocating way too much memory. - // We allow for each primitive to be the minimal 1 byte in size, and we have a key=value map, so that's 2 bytes. - // Formatters that know each element is larger can optionally add a stronger check. - ThrowInsufficientBufferUnless(this.reader.Remaining >= count * 2); - - return count; - } - - /// - /// Reads a map header from - /// , - /// , or - /// some built-in code between and - /// if there is sufficient buffer to read it. - /// - /// Receives the number of key=value pairs in the map if the entire map header can be read. - /// true if there was sufficient buffer and a map header was found; false if the buffer incompletely describes an map header. - /// Thrown if a code other than an map header is encountered. - /// - /// When this method returns false the position of the reader is left in an undefined position. - /// The caller is expected to recreate the reader (presumably with a longer sequence to read from) before continuing. - /// - public bool TryReadMapHeader(out int count) - { - count = -1; - if (!this.reader.TryRead(out byte code)) - { - return false; - } - - switch (code) - { - case MessagePackCode.Map16: - if (!this.reader.TryReadBigEndian(out short shortValue)) - { - return false; - } - - count = unchecked((ushort)shortValue); - break; - case MessagePackCode.Map32: - if (!this.reader.TryReadBigEndian(out int intValue)) - { - return false; - } - - count = intValue; - break; - default: - if (code >= MessagePackCode.MinFixMap && code <= MessagePackCode.MaxFixMap) - { - count = (byte)(code & 0xF); - break; - } - - throw ThrowInvalidCode(code); - } - - return true; - } - - /// - /// Reads a boolean value from either a or . - /// - /// The value. - public bool ReadBoolean() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - switch (code) - { - case MessagePackCode.True: - return true; - case MessagePackCode.False: - return false; - default: - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a from any of: - /// , - /// , - /// or anything between and . - /// - /// A character. - public char ReadChar() => (char)this.ReadUInt16(); - - /// - /// Reads an value from any value encoded with: - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// or some value between and , - /// or some value between and . - /// - /// The value. - public unsafe float ReadSingle() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.Float32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out float floatValue)); - return floatValue; - case MessagePackCode.Float64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out double doubleValue)); - return (float)doubleValue; - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteValue)); - return sbyteValue; - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortValue)); - return shortValue; - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return intValue; - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longValue)); - return longValue; - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteValue)); - return byteValue; - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortValue)); - return ushortValue; - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintValue)); - return uintValue; - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongValue)); - return ulongValue; - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return unchecked((sbyte)code); - } - else if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from any value encoded with: - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// or some value between and , - /// or some value between and . - /// - /// The value. - public unsafe double ReadDouble() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.Float64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out double doubleValue)); - return doubleValue; - case MessagePackCode.Float32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out float floatValue)); - return floatValue; - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteValue)); - return unchecked((sbyte)byteValue); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortValue)); - return shortValue; - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return intValue; - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longValue)); - return longValue; - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byteValue)); - return byteValue; - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out shortValue)); - return unchecked((ushort)shortValue); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out intValue)); - return unchecked((uint)intValue); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out longValue)); - return unchecked((ulong)longValue); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return unchecked((sbyte)code); - } - else if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads a from a value encoded with - /// , - /// , or - /// . - /// Expects extension type code . - /// - /// The value. - public DateTime ReadDateTime() => this.ReadDateTime(this.ReadExtensionFormatHeader()); - - /// - /// Reads a from a value encoded with - /// , - /// , - /// . - /// Expects extension type code . - /// - /// The extension header that was already read. - /// The value. - public DateTime ReadDateTime(ExtensionHeader header) - { - if (header.TypeCode != ReservedMessagePackExtensionTypeCode.DateTime) - { - throw new MessagePackSerializationException(string.Format("Extension TypeCode is invalid. typeCode: {0}", header.TypeCode)); - } - - switch (header.Length) - { - case 4: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intValue)); - return DateTimeConstants.UnixEpoch.AddSeconds(unchecked((uint)intValue)); - case 8: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longValue)); - ulong ulongValue = unchecked((ulong)longValue); - long nanoseconds = (long)(ulongValue >> 34); - ulong seconds = ulongValue & 0x00000003ffffffffL; - return DateTimeConstants.UnixEpoch.AddSeconds(seconds).AddTicks(nanoseconds / DateTimeConstants.NanosecondsPerTick); - case 12: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out intValue)); - nanoseconds = unchecked((uint)intValue); - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out longValue)); - return DateTimeConstants.UnixEpoch.AddSeconds(longValue).AddTicks(nanoseconds / DateTimeConstants.NanosecondsPerTick); - default: - throw new MessagePackSerializationException($"Length of extension was {header.Length}. Either 4 or 8 were expected."); - } - } - - /// - /// Reads a span of bytes, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or to support OldSpec compatibility: - /// , - /// , - /// or something between and . - /// - /// - /// A sequence of bytes, or null if the read token is . - /// The data is a slice from the original sequence passed to this reader's constructor. - /// - public ReadOnlySequence? ReadBytes() - { - if (this.TryReadNil()) - { - return null; - } - - int length = this.GetBytesLength(); - ThrowInsufficientBufferUnless(this.reader.Remaining >= length); - ReadOnlySequence result = this.reader.Sequence.Slice(this.reader.Position, length); - this.reader.Advance(length); - return result; - } - - /// - /// Reads a string of bytes, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or a code between and . - /// - /// - /// The sequence of bytes, or null if the read token is . - /// The data is a slice from the original sequence passed to this reader's constructor. - /// - public ReadOnlySequence? ReadStringSequence() - { - if (this.TryReadNil()) - { - return null; - } - - int length = this.GetStringLengthInBytes(); - ThrowInsufficientBufferUnless(this.reader.Remaining >= length); - ReadOnlySequence result = this.reader.Sequence.Slice(this.reader.Position, length); - this.reader.Advance(length); - return result; - } - - /// - /// Reads a string of bytes, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or a code between and . - /// - /// Receives the span to the string. - /// - /// true if the string is contiguous in memory such that it could be set as a single span. - /// false if the read token is or the string is not in a contiguous span. - /// - /// - /// Callers should generally be prepared for a false result and failover to calling - /// which can represent a null result and handle strings that are not contiguous in memory. - /// - public bool TryReadStringSpan(out ReadOnlySpan span) - { - if (this.IsNil) - { - span = default; - return false; - } - - long oldPosition = this.reader.Consumed; - int length = this.GetStringLengthInBytes(); - ThrowInsufficientBufferUnless(this.reader.Remaining >= length); - - if (this.reader.CurrentSpanIndex + length <= this.reader.CurrentSpan.Length) - { - span = this.reader.CurrentSpan.Slice(this.reader.CurrentSpanIndex, length); - this.reader.Advance(length); - return true; - } - else - { - this.reader.Rewind(this.reader.Consumed - oldPosition); - span = default; - return false; - } - } - - /// - /// Reads a string, whose length is determined by a header of one of these types: - /// , - /// , - /// , - /// or a code between and . - /// - /// A string, or null if the current msgpack token is . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public string ReadString() - { - if (this.TryReadNil()) - { - return null; - } - - int byteLength = this.GetStringLengthInBytes(); - - ReadOnlySpan unreadSpan = this.reader.UnreadSpan; - //UnityEngine.Debug.Log(reader.CurrentSpan[0]); - //UnityEngine.Debug.Log(unreadSpan[0]); - if (unreadSpan.Length >= byteLength) - { - // Fast path: all bytes to decode appear in the same span. - string value = StringEncoding.UTF8.GetString(unreadSpan.Slice(0, byteLength)); - this.reader.Advance(byteLength); - return value; - } - else - { - return this.ReadStringSlow(byteLength); - } - } - - /// - /// Reads an extension format header, based on one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// The extension header. - /// - /// Thrown if the header cannot be read in the bytes left in the - /// or if it is clear that there are insufficient bytes remaining after the header to include all the bytes the header claims to be there. - /// - /// Thrown if a code other than an extension format header is encountered. - public ExtensionHeader ReadExtensionFormatHeader() - { - ThrowInsufficientBufferUnless(this.TryReadExtensionFormatHeader(out ExtensionHeader header)); - - // Protect against corrupted or mischievious data that may lead to allocating way too much memory. - ThrowInsufficientBufferUnless(this.reader.Remaining >= header.Length); - - return header; - } - - /// - /// Reads an extension format header, based on one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// - /// if there is sufficient buffer to read it. - /// - /// Receives the extension header if the remaining bytes in the fully describe the header. - /// The number of key=value pairs in the map. - /// Thrown if a code other than an extension format header is encountered. - /// - /// When this method returns false the position of the reader is left in an undefined position. - /// The caller is expected to recreate the reader (presumably with a longer sequence to read from) before continuing. - /// - public bool TryReadExtensionFormatHeader(out ExtensionHeader extensionHeader) - { - extensionHeader = default; - if (!this.reader.TryRead(out byte code)) - { - return false; - } - - uint length; - switch (code) - { - case MessagePackCode.FixExt1: - length = 1; - break; - case MessagePackCode.FixExt2: - length = 2; - break; - case MessagePackCode.FixExt4: - length = 4; - break; - case MessagePackCode.FixExt8: - length = 8; - break; - case MessagePackCode.FixExt16: - length = 16; - break; - case MessagePackCode.Ext8: - if (!this.reader.TryRead(out byte byteLength)) - { - return false; - } - - length = byteLength; - break; - case MessagePackCode.Ext16: - if (!this.reader.TryReadBigEndian(out short shortLength)) - { - return false; - } - - length = unchecked((ushort)shortLength); - break; - case MessagePackCode.Ext32: - if (!this.reader.TryReadBigEndian(out int intLength)) - { - return false; - } - - length = unchecked((uint)intLength); - break; - default: - throw ThrowInvalidCode(code); - } - - if (!this.reader.TryRead(out byte typeCode)) - { - return false; - } - - extensionHeader = new ExtensionHeader(unchecked((sbyte)typeCode), length); - return true; - } - - /// - /// Reads an extension format header and data, based on one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// - /// The extension format. - /// The data is a slice from the original sequence passed to this reader's constructor. - /// - public ExtensionResult ReadExtensionFormat() - { - ExtensionHeader header = this.ReadExtensionFormatHeader(); - try - { - ReadOnlySequence data = this.reader.Sequence.Slice(this.reader.Position, header.Length); - this.reader.Advance(header.Length); - return new ExtensionResult(header.TypeCode, data); - } - catch (ArgumentOutOfRangeException ex) - { - throw ThrowNotEnoughBytesException(ex); - } - } - - /// - /// Throws an exception indicating that there aren't enough bytes remaining in the buffer to store - /// the promised data. - /// - private static EndOfStreamException ThrowNotEnoughBytesException() => throw new EndOfStreamException(); - - /// - /// Throws an exception indicating that there aren't enough bytes remaining in the buffer to store - /// the promised data. - /// - private static EndOfStreamException ThrowNotEnoughBytesException(Exception innerException) => throw new EndOfStreamException(new EndOfStreamException().Message, innerException); - - /// - /// Throws an explaining an unexpected code was encountered. - /// - /// The code that was encountered. - /// Nothing. This method always throws. - private static Exception ThrowInvalidCode(byte code) - { - throw new MessagePackSerializationException(string.Format("Unexpected msgpack code {0} ({1}) encountered.", code, MessagePackCode.ToFormatName(code))); - } - - /// - /// Throws if a condition is false. - /// - /// A boolean value. - /// Thrown if is false. - private static void ThrowInsufficientBufferUnless(bool condition) - { - if (!condition) - { - ThrowNotEnoughBytesException(); - } - } - - private int GetBytesLength() - { - ThrowInsufficientBufferUnless(this.TryGetBytesLength(out int length)); - return length; - } - - private bool TryGetBytesLength(out int length) - { - if (!this.reader.TryRead(out byte code)) - { - length = 0; - return false; - } - - // In OldSpec mode, Bin didn't exist, so Str was used. Str8 didn't exist either. - switch (code) - { - case MessagePackCode.Bin8: - if (this.reader.TryRead(out byte byteLength)) - { - length = byteLength; - return true; - } - - break; - case MessagePackCode.Bin16: - case MessagePackCode.Str16: // OldSpec compatibility - if (this.reader.TryReadBigEndian(out short shortLength)) - { - length = unchecked((ushort)shortLength); - return true; - } - - break; - case MessagePackCode.Bin32: - case MessagePackCode.Str32: // OldSpec compatibility - if (this.reader.TryReadBigEndian(out length)) - { - return true; - } - - break; - default: - // OldSpec compatibility - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - length = code & 0x1F; - return true; - } - - throw ThrowInvalidCode(code); - } - - length = 0; - return false; - } - - /// - /// Gets the length of the next string. - /// - /// Receives the length of the next string, if there were enough bytes to read it. - /// true if there were enough bytes to read the length of the next string; false otherwise. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool TryGetStringLengthInBytes(out int length) - { - if (!this.reader.TryRead(out byte code)) - { - length = 0; - return false; - } - - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - length = code & 0x1F; - return true; - } - - return this.TryGetStringLengthInBytesSlow(code, out length); - } - - /// - /// Gets the length of the next string. - /// - /// The length of the next string. - private int GetStringLengthInBytes() - { - ThrowInsufficientBufferUnless(this.TryGetStringLengthInBytes(out int length)); - return length; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool TryGetStringLengthInBytesSlow(byte code, out int length) - { - switch (code) - { - case MessagePackCode.Str8: - if (this.reader.TryRead(out byte byteValue)) - { - length = byteValue; - return true; - } - - break; - case MessagePackCode.Str16: - if (this.reader.TryReadBigEndian(out short shortValue)) - { - length = unchecked((ushort)shortValue); - return true; - } - - break; - case MessagePackCode.Str32: - if (this.reader.TryReadBigEndian(out int intValue)) - { - length = intValue; - return true; - } - - break; - default: - if (code >= MessagePackCode.MinFixStr && code <= MessagePackCode.MaxFixStr) - { - length = code & 0x1F; - return true; - } - - throw ThrowInvalidCode(code); - } - - length = 0; - return false; - } - - /// - /// Reads a string assuming that it is spread across multiple spans in the . - /// - /// The length of the string to be decoded, in bytes. - /// The decoded string. - private string ReadStringSlow(int byteLength) - { - ThrowInsufficientBufferUnless(this.reader.Remaining >= byteLength); - - // We need to decode bytes incrementally across multiple spans. - int maxCharLength = StringEncoding.UTF8.GetMaxCharCount(byteLength); - char[] charArray = ArrayPool.Shared.Rent(maxCharLength); - System.Text.Decoder decoder = StringEncoding.UTF8.GetDecoder(); - - int remainingByteLength = byteLength; - int initializedChars = 0; - while (remainingByteLength > 0) - { - int bytesRead = Math.Min(remainingByteLength, this.reader.UnreadSpan.Length); - remainingByteLength -= bytesRead; - bool flush = remainingByteLength == 0; -#if NETCOREAPP - initializedChars += decoder.GetChars(this.reader.UnreadSpan.Slice(0, bytesRead), charArray.AsSpan(initializedChars), flush); -#else - unsafe - { - fixed (byte* pUnreadSpan = this.reader.UnreadSpan) - fixed (char* pCharArray = &charArray[initializedChars]) - { - initializedChars += decoder.GetChars(pUnreadSpan, bytesRead, pCharArray, charArray.Length - initializedChars, flush); - } - } -#endif - this.reader.Advance(bytesRead); - } - - string value = new string(charArray, 0, initializedChars); - ArrayPool.Shared.Return(charArray); - return value; - } - - private bool TrySkipNextArray() => this.TryReadArrayHeader(out int count) && this.TrySkip(count); - - private bool TrySkipNextMap() => this.TryReadMapHeader(out int count) && this.TrySkip(count * 2); - - private bool TrySkip(int count) - { - for (int i = 0; i < count; i++) - { - if (!this.TrySkip()) - { - return false; - } - } - - return true; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackReader.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackReader.cs.meta deleted file mode 100644 index 93200f5..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 80f6863e06d288f489fcea7b5654b2cb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSecurity.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSecurity.cs deleted file mode 100644 index c362f91..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSecurity.cs +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.ExceptionServices; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack -{ - /// - /// Settings related to security, particularly relevant when deserializing data from untrusted sources. - /// - public class MessagePackSecurity - { - /// - /// Gets an instance preconfigured with settings that omit all protections. Useful for deserializing fully-trusted and valid msgpack sequences. - /// - public static readonly MessagePackSecurity TrustedData = new MessagePackSecurity(); - - /// - /// Gets an instance preconfigured with protections applied with reasonable settings for deserializing untrusted msgpack sequences. - /// - public static readonly MessagePackSecurity UntrustedData = new MessagePackSecurity - { - HashCollisionResistant = true, - MaximumObjectGraphDepth = 500, - }; - - private readonly ObjectFallbackEqualityComparer objectFallbackEqualityComparer; - - private MessagePackSecurity() - { - this.objectFallbackEqualityComparer = new ObjectFallbackEqualityComparer(this); - } - - /// - /// Initializes a new instance of the class - /// with properties copied from a provided template. - /// - /// The template to copy from. - protected MessagePackSecurity(MessagePackSecurity copyFrom) - : this() - { - if (copyFrom is null) - { - throw new ArgumentNullException(nameof(copyFrom)); - } - - this.HashCollisionResistant = copyFrom.HashCollisionResistant; - this.MaximumObjectGraphDepth = copyFrom.MaximumObjectGraphDepth; - } - - /// - /// Gets a value indicating whether data to be deserialized is untrusted and thus should not be allowed to create - /// dictionaries or other hash-based collections unless the hashed type has a hash collision resistant implementation available. - /// This can mitigate some denial of service attacks when deserializing untrusted code. - /// - /// - /// The value is false for and true for . - /// - public bool HashCollisionResistant { get; private set; } - - /// - /// Gets the maximum depth of an object graph that may be deserialized. - /// - /// - /// - /// This value can be reduced to avoid a stack overflow that would crash the process when deserializing a msgpack sequence designed to cause deep recursion. - /// A very short callstack on a thread with 1MB of total stack space might deserialize ~2000 nested arrays before crashing due to a stack overflow. - /// Since stack space occupied may vary by the kind of object deserialized, a conservative value for this property to defend against stack overflow attacks might be 500. - /// - /// - public int MaximumObjectGraphDepth { get; private set; } = int.MaxValue; - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSecurity WithMaximumObjectGraphDepth(int maximumObjectGraphDepth) - { - if (this.MaximumObjectGraphDepth == maximumObjectGraphDepth) - { - return this; - } - - var clone = this.Clone(); - clone.MaximumObjectGraphDepth = maximumObjectGraphDepth; - return clone; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSecurity WithHashCollisionResistant(bool hashCollisionResistant) - { - if (this.HashCollisionResistant == hashCollisionResistant) - { - return this; - } - - var clone = this.Clone(); - clone.HashCollisionResistant = hashCollisionResistant; - return clone; - } - - /// - /// Gets an that is suitable to use with a hash-based collection. - /// - /// The type of key that will be hashed in the collection. - /// The to use. - /// - /// When is active, this will be a collision resistant instance which may reject certain key types. - /// When is not active, this will be . - /// - public IEqualityComparer GetEqualityComparer() - { - return this.HashCollisionResistant ? GetHashCollisionResistantEqualityComparer() : EqualityComparer.Default; - } - - /// - /// Gets an that is suitable to use with a hash-based collection. - /// - /// The to use. - /// - /// When is active, this will be a collision resistant instance which may reject certain key types. - /// When is not active, this will be . - /// - public IEqualityComparer GetEqualityComparer() - { - return this.HashCollisionResistant ? GetHashCollisionResistantEqualityComparer() : EqualityComparer.Default; - } - - /// - /// Returns a hash collision resistant equality comparer. - /// - /// The type of key that will be hashed in the collection. - /// A hash collision resistant equality comparer. - protected virtual IEqualityComparer GetHashCollisionResistantEqualityComparer() - { - IEqualityComparer result = null; - if (typeof(T).GetTypeInfo().IsEnum) - { - Type underlyingType = typeof(T).GetTypeInfo().GetEnumUnderlyingType(); - result = - underlyingType == typeof(sbyte) ? CollisionResistantHasher.Instance : - underlyingType == typeof(byte) ? CollisionResistantHasher.Instance : - underlyingType == typeof(short) ? CollisionResistantHasher.Instance : - underlyingType == typeof(ushort) ? CollisionResistantHasher.Instance : - underlyingType == typeof(int) ? CollisionResistantHasher.Instance : - underlyingType == typeof(uint) ? CollisionResistantHasher.Instance : - null; - } - else - { - // For anything 32-bits and under, our fallback base secure hasher is usually adequate since it makes the hash unpredictable. - // We should have special implementations for any value that is larger than 32-bits in order to make sure - // that all the data gets hashed securely rather than trivially and predictably compressed into 32-bits before being hashed. - // We also have to specially handle some 32-bit types (e.g. float) where multiple in-memory representations should hash to the same value. - // Any type supported by the PrimitiveObjectFormatter should be added here if supporting it as a key in a collection makes sense. - result = - // 32-bits or smaller: - typeof(T) == typeof(bool) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(char) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(sbyte) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(byte) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(short) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(ushort) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(int) ? CollisionResistantHasher.Instance : - typeof(T) == typeof(uint) ? CollisionResistantHasher.Instance : - - // Larger than 32-bits (or otherwise require special handling): - typeof(T) == typeof(long) ? (IEqualityComparer)Int64EqualityComparer.Instance : - typeof(T) == typeof(ulong) ? (IEqualityComparer)UInt64EqualityComparer.Instance : - typeof(T) == typeof(float) ? (IEqualityComparer)SingleEqualityComparer.Instance : - typeof(T) == typeof(double) ? (IEqualityComparer)DoubleEqualityComparer.Instance : - typeof(T) == typeof(string) ? (IEqualityComparer)StringEqualityComparer.Instance : - typeof(T) == typeof(Guid) ? (IEqualityComparer)GuidEqualityComparer.Instance : - typeof(T) == typeof(DateTime) ? (IEqualityComparer)DateTimeEqualityComparer.Instance : - typeof(T) == typeof(DateTimeOffset) ? (IEqualityComparer)DateTimeOffsetEqualityComparer.Instance : - typeof(T) == typeof(object) ? (IEqualityComparer)this.objectFallbackEqualityComparer : - null; - } - - // Any type we don't explicitly whitelist here shouldn't be allowed to use as the key in a hash-based collection since it isn't known to be hash resistant. - // This method can of course be overridden to add more hash collision resistant type support, or the deserializing party can indicate that the data is Trusted - // so that this method doesn't even get called. - return result ?? throw new TypeAccessException($"No hash-resistant equality comparer available for type: {typeof(T)}"); - } - - /// - /// Checks the depth of the deserializing graph and increments it by 1. - /// - /// The reader that is involved in deserialization. - /// - /// Callers should decrement after exiting that edge in the graph. - /// - /// Thrown if is already at or exceeds . - /// - /// Rather than wrap the body of every method, - /// this should wrap *calls* to these methods. They need not appear in pure "thunk" methods that simply delegate the deserialization to another formatter. - /// In this way, we can avoid repeatedly incrementing and decrementing the counter when deserializing each element of a collection. - /// - public void DepthStep(ref MessagePackReader reader) - { - if (reader.Depth >= this.MaximumObjectGraphDepth) - { - throw new InsufficientExecutionStackException($"This msgpack sequence has an object graph that exceeds the maximum depth allowed of {MaximumObjectGraphDepth}."); - } - - reader.Depth++; - } - - /// - /// Returns a hash collision resistant equality comparer. - /// - /// A hash collision resistant equality comparer. - protected virtual IEqualityComparer GetHashCollisionResistantEqualityComparer() => (IEqualityComparer)this.GetHashCollisionResistantEqualityComparer(); - - /// - /// Creates a new instance that is a copy of this one. - /// - /// - /// Derived types should override this method to instantiate their own derived type. - /// - protected virtual MessagePackSecurity Clone() => new MessagePackSecurity(this); - - /// - /// A hash collision resistant implementation of . - /// - /// The type of key that will be hashed. - private class CollisionResistantHasher : IEqualityComparer, IEqualityComparer - { - internal static readonly CollisionResistantHasher Instance = new CollisionResistantHasher(); - - public bool Equals(T x, T y) => EqualityComparer.Default.Equals(x, y); - - bool IEqualityComparer.Equals(object x, object y) => ((IEqualityComparer)EqualityComparer.Default).Equals(x, y); - - public int GetHashCode(object obj) => this.GetHashCode((T)obj); - - public virtual int GetHashCode(T value) => HashCode.Combine(value); - } - - /// - /// A special hash-resistent equality comparer that defers picking the actual implementation - /// till it can check the runtime type of each value to be hashed. - /// - private class ObjectFallbackEqualityComparer : IEqualityComparer, IEqualityComparer - { - private static readonly MethodInfo GetHashCollisionResistantEqualityComparerOpenGenericMethod = typeof(MessagePackSecurity).GetTypeInfo().DeclaredMethods.Single(m => m.Name == nameof(MessagePackSecurity.GetHashCollisionResistantEqualityComparer) && m.IsGenericMethod); - private readonly MessagePackSecurity security; - private readonly ThreadsafeTypeKeyHashTable equalityComparerCache = new ThreadsafeTypeKeyHashTable(); - - internal ObjectFallbackEqualityComparer(MessagePackSecurity security) - { - this.security = security ?? throw new ArgumentNullException(nameof(security)); - } - - bool IEqualityComparer.Equals(object x, object y) => EqualityComparer.Default.Equals(x, y); - - bool IEqualityComparer.Equals(object x, object y) => ((IEqualityComparer)EqualityComparer.Default).Equals(x, y); - - public int GetHashCode(object value) - { - if (value is null) - { - return 0; - } - - Type valueType = value.GetType(); - - // Take care to avoid recursion. - if (valueType == typeof(object)) - { - // We can trust object.GetHashCode() to be collision resistant. - return value.GetHashCode(); - } - - if (!equalityComparerCache.TryGetValue(valueType, out IEqualityComparer equalityComparer)) - { - try - { - equalityComparer = (IEqualityComparer)GetHashCollisionResistantEqualityComparerOpenGenericMethod.MakeGenericMethod(valueType).Invoke(this.security, Array.Empty()); - } - catch (TargetInvocationException ex) - { - ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); - } - - equalityComparerCache.TryAdd(valueType, equalityComparer); - } - - return equalityComparer.GetHashCode(value); - } - } - - private class UInt64EqualityComparer : CollisionResistantHasher - { - internal static new readonly UInt64EqualityComparer Instance = new UInt64EqualityComparer(); - - public override int GetHashCode(ulong value) => HashCode.Combine((uint)(value >> 32), unchecked((uint)value)); - } - - private class Int64EqualityComparer : CollisionResistantHasher - { - internal static new readonly Int64EqualityComparer Instance = new Int64EqualityComparer(); - - public override int GetHashCode(long value) => HashCode.Combine((int)(value >> 32), unchecked((int)value)); - } - - private class SingleEqualityComparer : CollisionResistantHasher - { - internal static new readonly SingleEqualityComparer Instance = new SingleEqualityComparer(); - - public override unsafe int GetHashCode(float value) - { - // Special check for 0.0 so that the hash of 0.0 and -0.0 will equal. - if (value == 0.0f) - { - return HashCode.Combine(0); - } - - // Standardize on the binary representation of NaN prior to hashing. - if (float.IsNaN(value)) - { - value = float.NaN; - } - - long l = *(long*)&value; - return HashCode.Combine((int)(l >> 32), unchecked((int)l)); - } - } - - private class DoubleEqualityComparer : CollisionResistantHasher - { - internal static new readonly DoubleEqualityComparer Instance = new DoubleEqualityComparer(); - - public override unsafe int GetHashCode(double value) - { - // Special check for 0.0 so that the hash of 0.0 and -0.0 will equal. - if (value == 0.0) - { - return HashCode.Combine(0); - } - - // Standardize on the binary representation of NaN prior to hashing. - if (double.IsNaN(value)) - { - value = double.NaN; - } - - long l = *(long*)&value; - return HashCode.Combine((int)(l >> 32), unchecked((int)l)); - } - } - - private class GuidEqualityComparer : CollisionResistantHasher - { - internal static new readonly GuidEqualityComparer Instance = new GuidEqualityComparer(); - - public override unsafe int GetHashCode(Guid value) - { - var hash = default(HashCode); - int* pGuid = (int*)&value; - for (int i = 0; i < sizeof(Guid) / sizeof(int); i++) - { - hash.Add(pGuid[i]); - } - - return hash.ToHashCode(); - } - } - - private class StringEqualityComparer : CollisionResistantHasher - { - internal static new readonly StringEqualityComparer Instance = new StringEqualityComparer(); - - public override int GetHashCode(string value) - { -#if NETCOREAPP - // .NET Core already has a secure string hashing function. Just use it. - return value?.GetHashCode() ?? 0; -#else - var hash = default(HashCode); - for (int i = 0; i < value.Length; i++) - { - hash.Add(value[i]); - } - - return hash.ToHashCode(); -#endif - } - } - - private class DateTimeEqualityComparer : CollisionResistantHasher - { - internal static new readonly DateTimeEqualityComparer Instance = new DateTimeEqualityComparer(); - - public override unsafe int GetHashCode(DateTime value) => HashCode.Combine((int)(value.Ticks >> 32), unchecked((int)value.Ticks), value.Kind); - } - - private class DateTimeOffsetEqualityComparer : CollisionResistantHasher - { - internal static new readonly DateTimeOffsetEqualityComparer Instance = new DateTimeOffsetEqualityComparer(); - - public override unsafe int GetHashCode(DateTimeOffset value) => HashCode.Combine((int)(value.UtcTicks >> 32), unchecked((int)value.UtcTicks)); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSecurity.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSecurity.cs.meta deleted file mode 100644 index 988985b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSecurity.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a3c0e646c712f8d4f95190e18802ec99 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializationException.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializationException.cs deleted file mode 100644 index 85aa1ef..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializationException.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; - -namespace MessagePack -{ - /// - /// An exception thrown during serializing an object graph or deserializing a messagepack sequence. - /// - [Serializable] -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - class MessagePackSerializationException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public MessagePackSerializationException() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The exception message. - public MessagePackSerializationException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The exception message. - /// The inner exception. - public MessagePackSerializationException(string message, Exception inner) - : base(message, inner) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// Serialization info. - /// Serialization context. - protected MessagePackSerializationException( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializationException.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializationException.cs.meta deleted file mode 100644 index 31a06ea..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializationException.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 807a473ed38c2614db8e2e945c346dbb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.Json.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.Json.cs deleted file mode 100644 index 091e2a9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.Json.cs +++ /dev/null @@ -1,497 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Globalization; -using System.IO; -using System.Text; -using System.Threading; -using MessagePack.Formatters; -using Nerdbank.Streams; - -namespace MessagePack -{ - // JSON API - public partial class MessagePackSerializer - { - /// - /// Serialize an object to JSON string. - /// - /// Thrown if an error occurs during serialization. - public static void SerializeToJson(TextWriter textWriter, T obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var msgpackWriter = new MessagePackWriter(sequenceRental.Value) - { - CancellationToken = cancellationToken, - }; - Serialize(ref msgpackWriter, obj, options); - msgpackWriter.Flush(); - var msgpackReader = new MessagePackReader(sequenceRental.Value) - { - CancellationToken = cancellationToken, - }; - ConvertToJson(ref msgpackReader, textWriter, options); - } - } - - /// - /// Serialize an object to JSON string. - /// - /// Thrown if an error occurs during serialization. - public static string SerializeToJson(T obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var writer = new StringWriter(); - SerializeToJson(writer, obj, options, cancellationToken); - return writer.ToString(); - } - - /// - /// Convert a message-pack binary to a JSON string. - /// - /// Thrown if an error occurs while reading the messagepack data or writing out the JSON. - public static string ConvertToJson(ReadOnlyMemory bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) => ConvertToJson(new ReadOnlySequence(bytes), options, cancellationToken); - - /// - /// Convert a message-pack binary to a JSON string. - /// - /// Thrown if an error occurs while reading the messagepack data or writing out the JSON. - public static string ConvertToJson(in ReadOnlySequence bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var jsonWriter = new StringWriter(); - var reader = new MessagePackReader(bytes) - { - CancellationToken = cancellationToken, - }; - ConvertToJson(ref reader, jsonWriter, options); - return jsonWriter.ToString(); - } - - /// - /// Convert a message-pack binary to a JSON string. - /// - /// Thrown if an error occurs while reading the messagepack data or writing out the JSON. - public static void ConvertToJson(ref MessagePackReader reader, TextWriter jsonWriter, MessagePackSerializerOptions options = null) - { - if (reader.End) - { - return; - } - - options = options ?? DefaultOptions; - try - { - if (options.Compression.IsCompression()) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - if (TryDecompress(ref reader, scratchRental.Value)) - { - var scratchReader = new MessagePackReader(scratchRental.Value) - { - CancellationToken = reader.CancellationToken, - }; - if (scratchReader.End) - { - return; - } - - ToJsonCore(ref scratchReader, jsonWriter, options); - } - else - { - ToJsonCore(ref reader, jsonWriter, options); - } - } - } - else - { - ToJsonCore(ref reader, jsonWriter, options); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while translating msgpack to JSON.", ex); - } - } - - /// - /// Translates the given JSON to MessagePack. - /// - public static void ConvertFromJson(string str, ref MessagePackWriter writer, MessagePackSerializerOptions options = null) - { - using (var sr = new StringReader(str)) - { - ConvertFromJson(sr, ref writer, options); - } - } - - /// - /// Translates the given JSON to MessagePack. - /// - public static byte[] ConvertFromJson(string str, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - var writer = new MessagePackWriter(scratchRental.Value) - { - CancellationToken = cancellationToken, - }; - using (var sr = new StringReader(str)) - { - ConvertFromJson(sr, ref writer, options); - } - - writer.Flush(); - return scratchRental.Value.AsReadOnlySequence.ToArray(); - } - } - - /// - /// Translates the given JSON to MessagePack. - /// - public static void ConvertFromJson(TextReader reader, ref MessagePackWriter writer, MessagePackSerializerOptions options = null) - { - options = options ?? DefaultOptions; - if (options.Compression.IsCompression()) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - using (var jr = new TinyJsonReader(reader, false)) - { - FromJsonCore(jr, ref scratchWriter); - } - - scratchWriter.Flush(); - ToLZ4BinaryCore(scratchRental.Value, ref writer, options.Compression); - } - } - else - { - using (var jr = new TinyJsonReader(reader, false)) - { - FromJsonCore(jr, ref writer); - } - } - } - - private static uint FromJsonCore(TinyJsonReader jr, ref MessagePackWriter writer) - { - uint count = 0; - while (jr.Read()) - { - switch (jr.TokenType) - { - case TinyJsonToken.None: - break; - case TinyJsonToken.StartObject: - // Set up a scratch area to serialize the collection since we don't know its length yet, which must be written first. - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - var mapCount = FromJsonCore(jr, ref scratchWriter); - scratchWriter.Flush(); - - mapCount = mapCount / 2; // remove propertyname string count. - writer.WriteMapHeader(mapCount); - writer.WriteRaw(scratchRental.Value); - } - - count++; - break; - case TinyJsonToken.EndObject: - return count; // break - case TinyJsonToken.StartArray: - // Set up a scratch area to serialize the collection since we don't know its length yet, which must be written first. - using (var scratchRental = SequencePool.Shared.Rent()) - { - MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value); - var arrayCount = FromJsonCore(jr, ref scratchWriter); - scratchWriter.Flush(); - - writer.WriteArrayHeader(arrayCount); - writer.WriteRaw(scratchRental.Value); - } - - count++; - break; - case TinyJsonToken.EndArray: - return count; // break - case TinyJsonToken.Number: - ValueType v = jr.ValueType; - if (v == ValueType.Double) - { - writer.Write(jr.DoubleValue); - } - else if (v == ValueType.Long) - { - writer.Write(jr.LongValue); - } - else if (v == ValueType.ULong) - { - writer.Write(jr.ULongValue); - } - else if (v == ValueType.Decimal) - { - DecimalFormatter.Instance.Serialize(ref writer, jr.DecimalValue, null); - } - - count++; - break; - case TinyJsonToken.String: - writer.Write(jr.StringValue); - count++; - break; - case TinyJsonToken.True: - writer.Write(true); - count++; - break; - case TinyJsonToken.False: - writer.Write(false); - count++; - break; - case TinyJsonToken.Null: - writer.WriteNil(); - count++; - break; - default: - break; - } - } - - return count; - } - - private static void ToJsonCore(ref MessagePackReader reader, TextWriter writer, MessagePackSerializerOptions options) - { - MessagePackType type = reader.NextMessagePackType; - switch (type) - { - case MessagePackType.Integer: - if (MessagePackCode.IsSignedInteger(reader.NextCode)) - { - writer.Write(reader.ReadInt64().ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.Write(reader.ReadUInt64().ToString(CultureInfo.InvariantCulture)); - } - - break; - case MessagePackType.Boolean: - writer.Write(reader.ReadBoolean() ? "true" : "false"); - break; - case MessagePackType.Float: - if (reader.NextCode == MessagePackCode.Float32) - { - writer.Write(reader.ReadSingle().ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.Write(reader.ReadDouble().ToString(CultureInfo.InvariantCulture)); - } - - break; - case MessagePackType.String: - WriteJsonString(reader.ReadString(), writer); - break; - case MessagePackType.Binary: - ArraySegment segment = ByteArraySegmentFormatter.Instance.Deserialize(ref reader, DefaultOptions); - writer.Write("\"" + Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) + "\""); - break; - case MessagePackType.Array: - { - int length = reader.ReadArrayHeader(); - options.Security.DepthStep(ref reader); - try - { - writer.Write("["); - for (int i = 0; i < length; i++) - { - ToJsonCore(ref reader, writer, options); - - if (i != length - 1) - { - writer.Write(","); - } - } - - writer.Write("]"); - } - finally - { - reader.Depth--; - } - - return; - } - - case MessagePackType.Map: - { - int length = reader.ReadMapHeader(); - options.Security.DepthStep(ref reader); - try - { - writer.Write("{"); - for (int i = 0; i < length; i++) - { - // write key - { - MessagePackType keyType = reader.NextMessagePackType; - if (keyType == MessagePackType.String || keyType == MessagePackType.Binary) - { - ToJsonCore(ref reader, writer, options); - } - else - { - writer.Write("\""); - ToJsonCore(ref reader, writer, options); - writer.Write("\""); - } - } - - writer.Write(":"); - - // write body - { - ToJsonCore(ref reader, writer, options); - } - - if (i != length - 1) - { - writer.Write(","); - } - } - - writer.Write("}"); - } - finally - { - reader.Depth--; - } - - return; - } - - case MessagePackType.Extension: - ExtensionHeader extHeader = reader.ReadExtensionFormatHeader(); - if (extHeader.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime) - { - DateTime dt = reader.ReadDateTime(extHeader); - writer.Write("\""); - writer.Write(dt.ToString("o", CultureInfo.InvariantCulture)); - writer.Write("\""); - } -#if !UNITY_2018_3_OR_NEWER - else if (extHeader.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter) - { - // prepare type name token - var privateBuilder = new StringBuilder(); - var typeNameTokenBuilder = new StringBuilder(); - SequencePosition positionBeforeTypeNameRead = reader.Position; - ToJsonCore(ref reader, new StringWriter(typeNameTokenBuilder), options); - int typeNameReadSize = (int)reader.Sequence.Slice(positionBeforeTypeNameRead, reader.Position).Length; - if (extHeader.Length > typeNameReadSize) - { - // object map or array - MessagePackType typeInside = reader.NextMessagePackType; - if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map) - { - privateBuilder.Append("{"); - } - - ToJsonCore(ref reader, new StringWriter(privateBuilder), options); - - // insert type name token to start of object map or array - if (typeInside != MessagePackType.Array) - { - typeNameTokenBuilder.Insert(0, "\"$type\":"); - } - - if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map) - { - privateBuilder.Append("}"); - } - - if (privateBuilder.Length > 2) - { - typeNameTokenBuilder.Append(","); - } - - privateBuilder.Insert(1, typeNameTokenBuilder.ToString()); - - writer.Write(privateBuilder.ToString()); - } - else - { - writer.Write("{\"$type\":\"" + typeNameTokenBuilder.ToString() + "}"); - } - } -#endif - else - { - var data = reader.ReadRaw((long)extHeader.Length); - writer.Write("["); - writer.Write(extHeader.TypeCode); - writer.Write(","); - writer.Write("\""); - writer.Write(Convert.ToBase64String(data.ToArray())); - writer.Write("\""); - writer.Write("]"); - } - - break; - case MessagePackType.Nil: - reader.Skip(); - writer.Write("null"); - break; - default: - throw new MessagePackSerializationException($"code is invalid. code: {reader.NextCode} format: {MessagePackCode.ToFormatName(reader.NextCode)}"); - } - } - - // escape string - private static void WriteJsonString(string value, TextWriter builder) - { - builder.Write('\"'); - - var len = value.Length; - for (int i = 0; i < len; i++) - { - var c = value[i]; - switch (c) - { - case '"': - builder.Write("\\\""); - break; - case '\\': - builder.Write("\\\\"); - break; - case '\b': - builder.Write("\\b"); - break; - case '\f': - builder.Write("\\f"); - break; - case '\n': - builder.Write("\\n"); - break; - case '\r': - builder.Write("\\r"); - break; - case '\t': - builder.Write("\\t"); - break; - default: - builder.Write(c); - break; - } - } - - builder.Write('\"'); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.Json.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.Json.cs.meta deleted file mode 100644 index a681b9c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.Json.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8b519a41377bf3a489ab6db1e1044458 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs deleted file mode 100644 index 281e20f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.IO; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; - -namespace MessagePack -{ - public partial class MessagePackSerializer - { - private static readonly Func CreateCompiledMethods; - private static readonly MessagePack.Internal.ThreadsafeTypeKeyHashTable Serializes = new MessagePack.Internal.ThreadsafeTypeKeyHashTable(capacity: 64); - - static MessagePackSerializer() - { - CreateCompiledMethods = t => new CompiledMethods(t); - } - - /// - public static void Serialize(Type type, ref MessagePackWriter writer, object obj, MessagePackSerializerOptions options = null) - { - GetOrAdd(type).Serialize_MessagePackWriter_T_Options.Invoke(ref writer, obj, options); - } - - /// - public static void Serialize(Type type, IBufferWriter writer, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - GetOrAdd(type).Serialize_IBufferWriter_T_Options_CancellationToken.Invoke(writer, obj, options, cancellationToken); - } - - /// - public static byte[] Serialize(Type type, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Serialize_T_Options.Invoke(obj, options, cancellationToken); - } - - /// - public static void Serialize(Type type, Stream stream, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - GetOrAdd(type).Serialize_Stream_T_Options_CancellationToken.Invoke(stream, obj, options, cancellationToken); - } - - /// - public static Task SerializeAsync(Type type, Stream stream, object obj, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).SerializeAsync_Stream_T_Options_CancellationToken.Invoke(stream, obj, options, cancellationToken); - } - - /// - public static object Deserialize(Type type, ref MessagePackReader reader, MessagePackSerializerOptions options = null) - { - return GetOrAdd(type).Deserialize_MessagePackReader_Options.Invoke(ref reader, options); - } - - /// - public static object Deserialize(Type type, Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Deserialize_Stream_Options_CancellationToken.Invoke(stream, options, cancellationToken); - } - - /// - public static ValueTask DeserializeAsync(Type type, Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).DeserializeAsync_Stream_Options_CancellationToken.Invoke(stream, options, cancellationToken); - } - - /// - public static object Deserialize(Type type, ReadOnlyMemory bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Deserialize_ReadOnlyMemory_Options.Invoke(bytes, options, cancellationToken); - } - - /// - public static object Deserialize(Type type, ReadOnlySequence bytes, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - return GetOrAdd(type).Deserialize_ReadOnlySequence_Options_CancellationToken.Invoke(bytes, options, cancellationToken); - } - - private static async ValueTask DeserializeObjectAsync(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken) => await DeserializeAsync(stream, options, cancellationToken).ConfigureAwait(false); - - private static CompiledMethods GetOrAdd(Type type) - { - return Serializes.GetOrAdd(type, CreateCompiledMethods); - } - - private class CompiledMethods - { - internal delegate void MessagePackWriterSerialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); - - internal delegate object MessagePackReaderDeserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); - - private const bool PreferInterpretation = -#if ENABLE_IL2CPP - true; -#else - false; -#endif - -#pragma warning disable SA1310 // Field names should not contain underscore -#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter -#pragma warning disable SA1401 // Fields should be private - internal readonly Func Serialize_T_Options; - internal readonly Action Serialize_Stream_T_Options_CancellationToken; - internal readonly Func SerializeAsync_Stream_T_Options_CancellationToken; - internal readonly MessagePackWriterSerialize Serialize_MessagePackWriter_T_Options; - internal readonly Action, object, MessagePackSerializerOptions, CancellationToken> Serialize_IBufferWriter_T_Options_CancellationToken; - - internal readonly MessagePackReaderDeserialize Deserialize_MessagePackReader_Options; - internal readonly Func Deserialize_Stream_Options_CancellationToken; - internal readonly Func> DeserializeAsync_Stream_Options_CancellationToken; - - internal readonly Func, MessagePackSerializerOptions, CancellationToken, object> Deserialize_ReadOnlyMemory_Options; - internal readonly Func, MessagePackSerializerOptions, CancellationToken, object> Deserialize_ReadOnlySequence_Options_CancellationToken; -#pragma warning restore SA1401 // Fields should be private -#pragma warning restore SA1307 // Accessible fields should begin with upper-case letter -#pragma warning restore SA1310 // Field names should not contain underscore - - internal CompiledMethods(Type type) - { - TypeInfo ti = type.GetTypeInfo(); - { - // public static byte[] Serialize(T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.Serialize_T_Options = (x, y, z) => (byte[])serialize.Invoke(null, new object[] { x, y, z }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - ti.IsValueType ? Expression.Unbox(param1, type) : Expression.Convert(param1, type), - param2, - param3); - Func lambda = Expression.Lambda>(body, param1, param2, param3).Compile(PreferInterpretation); - - this.Serialize_T_Options = lambda; -#endif - } - - { - // public static void Serialize(Stream stream, T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { typeof(Stream), null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.Serialize_Stream_T_Options_CancellationToken = (x, y, z, a) => serialize.Invoke(null, new object[] { x, y, z, a }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param4 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3, - param4); - Action lambda = Expression.Lambda>(body, param1, param2, param3, param4).Compile(PreferInterpretation); - - this.Serialize_Stream_T_Options_CancellationToken = lambda; -#endif - } - - { - // public static Task SerializeAsync(Stream stream, T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(SerializeAsync), type, new Type[] { typeof(Stream), null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.SerializeAsync_Stream_T_Options_CancellationToken = (x, y, z, a) => (Task)serialize.Invoke(null, new object[] { x, y, z, a }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param4 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3, - param4); - Func lambda = Expression.Lambda>(body, param1, param2, param3, param4).Compile(PreferInterpretation); - - this.SerializeAsync_Stream_T_Options_CancellationToken = lambda; -#endif - } - - { - // public static Task Serialize(IBufferWriter writer, T obj, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { typeof(IBufferWriter), null, typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.Serialize_IBufferWriter_T_Options_CancellationToken = (x, y, z, a) => serialize.Invoke(null, new object[] { x, y, z, a }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(IBufferWriter), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param4 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3, - param4); - Action, object, MessagePackSerializerOptions, CancellationToken> lambda = Expression.Lambda, object, MessagePackSerializerOptions, CancellationToken>>(body, param1, param2, param3, param4).Compile(PreferInterpretation); - - this.Serialize_IBufferWriter_T_Options_CancellationToken = lambda; -#endif - } - - { - // public static void Serialize(ref MessagePackWriter writer, T obj, MessagePackSerializerOptions options) - MethodInfo serialize = GetMethod(nameof(Serialize), type, new Type[] { typeof(MessagePackWriter).MakeByRefType(), null, typeof(MessagePackSerializerOptions) }); -#if ENABLE_IL2CPP - this.Serialize_MessagePackWriter_T_Options = (ref MessagePackWriter x, object y, MessagePackSerializerOptions z) => ThrowRefStructNotSupported(); -#else - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer"); - ParameterExpression param2 = Expression.Parameter(typeof(object), "obj"); - ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - - MethodCallExpression body = Expression.Call( - null, - serialize, - param1, - ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type), - param3); - MessagePackWriterSerialize lambda = Expression.Lambda(body, param1, param2, param3).Compile(PreferInterpretation); - - this.Serialize_MessagePackWriter_T_Options = lambda; -#endif - } - - { - // public static T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); -#if ENABLE_IL2CPP - this.Deserialize_MessagePackReader_Options = (ref MessagePackReader reader, MessagePackSerializerOptions options) => { ThrowRefStructNotSupported(); return null; }; -#else - ParameterExpression param1 = Expression.Parameter(typeof(MessagePackReader).MakeByRefType(), "reader"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2), typeof(object)); - MessagePackReaderDeserialize lambda = Expression.Lambda(body, param1, param2).Compile(); - - this.Deserialize_MessagePackReader_Options = lambda; -#endif - } - - { - // public static T Deserialize(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(Stream), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.Deserialize_Stream_Options_CancellationToken = (x, y, z) => deserialize.Invoke(null, new object[] { x, y, z }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(object)); - Func lambda = Expression.Lambda>(body, param1, param2, param3).Compile(PreferInterpretation); - - this.Deserialize_Stream_Options_CancellationToken = lambda; -#endif - } - - { - // public static ValueTask DeserializeObjectAsync(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(DeserializeObjectAsync), type, new Type[] { typeof(Stream), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.DeserializeAsync_Stream_Options_CancellationToken = (x, y, z) => (ValueTask)deserialize.Invoke(null, new object[] { x, y, z }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(Stream), "stream"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(ValueTask)); - Func> lambda = Expression.Lambda>>(body, param1, param2, param3).Compile(PreferInterpretation); - - this.DeserializeAsync_Stream_Options_CancellationToken = lambda; -#endif - } - - { - // public static T Deserialize(ReadOnlyMemory bytes, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(ReadOnlyMemory), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.Deserialize_ReadOnlyMemory_Options = (x, y, z) => deserialize.Invoke(null, new object[] { x, y, z }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(ReadOnlyMemory), "bytes"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(object)); - Func, MessagePackSerializerOptions, CancellationToken, object> lambda = Expression.Lambda, MessagePackSerializerOptions, CancellationToken, object>>(body, param1, param2, param3).Compile(PreferInterpretation); - - this.Deserialize_ReadOnlyMemory_Options = lambda; -#endif - } - - { - // public static T Deserialize(ReadOnlySequence bytes, MessagePackSerializerOptions options, CancellationToken cancellationToken) - MethodInfo deserialize = GetMethod(nameof(Deserialize), type, new Type[] { typeof(ReadOnlySequence).MakeByRefType(), typeof(MessagePackSerializerOptions), typeof(CancellationToken) }); -#if ENABLE_IL2CPP - this.Deserialize_ReadOnlySequence_Options_CancellationToken = (x, y, z) => deserialize.Invoke(null, new object[] { x, y, z }); -#else - ParameterExpression param1 = Expression.Parameter(typeof(ReadOnlySequence), "bytes"); - ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options"); - ParameterExpression param3 = Expression.Parameter(typeof(CancellationToken), "cancellationToken"); - UnaryExpression body = Expression.Convert(Expression.Call(null, deserialize, param1, param2, param3), typeof(object)); - Func, MessagePackSerializerOptions, CancellationToken, object> lambda = Expression.Lambda, MessagePackSerializerOptions, CancellationToken, object>>(body, param1, param2, param3).Compile(PreferInterpretation); - - this.Deserialize_ReadOnlySequence_Options_CancellationToken = lambda; -#endif - } - } - - private static void ThrowRefStructNotSupported() - { - // C# 8.0 is not supported call `ref struct` via reflection. (It is milestoned at .NET 6) - throw new NotSupportedException("MessagePackWriter/Reader overload is not supported in MessagePackSerializer.NonGenerics."); - } - - // null is generic type marker. - private static MethodInfo GetMethod(string methodName, Type type, Type[] parameters) - { - return typeof(MessagePackSerializer).GetRuntimeMethods().Single(x => - { - if (methodName != x.Name) - { - return false; - } - - ParameterInfo[] ps = x.GetParameters(); - if (ps.Length != parameters.Length) - { - return false; - } - - for (int i = 0; i < ps.Length; i++) - { - if (parameters[i] == null && ps[i].ParameterType.IsGenericParameter) - { - continue; - } - - if (ps[i].ParameterType != parameters[i]) - { - return false; - } - } - - return true; - }) - .MakeGenericMethod(type); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs.meta deleted file mode 100644 index 3add0b0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.NonGeneric.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e094e2dba201ea84ba880d525ce8532e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.cs deleted file mode 100644 index 973f422..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.cs +++ /dev/null @@ -1,671 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Diagnostics; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using MessagePack.LZ4; -using Nerdbank.Streams; - -namespace MessagePack -{ - /// - /// High-Level API of MessagePack for C#. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Each overload has sufficiently unique required parameters.")] - public static partial class MessagePackSerializer - { - private const int LZ4NotCompressionSizeInLz4BlockType = 64; - private const int MaxHintSize = 1024 * 1024; - - /// - /// Gets or sets the default set of options to use when not explicitly specified for a method call. - /// - /// The default value is . - /// - /// This is an AppDomain or process-wide setting. - /// If you're writing a library, you should NOT set or rely on this property but should instead pass - /// in (or the required options) explicitly to every method call - /// to guarantee appropriate behavior in any application. - /// If you are an app author, realize that setting this property impacts the entire application so it should only be - /// set once, and before any use of occurs. - /// - public static MessagePackSerializerOptions DefaultOptions { get; set; } = MessagePackSerializerOptions.Standard; - - /// - /// A thread-local, recyclable array that may be used for short bursts of code. - /// - [ThreadStatic] - private static byte[] scratchArray; - - /// - /// Serializes a given value with the specified buffer writer. - /// - /// The buffer writer to serialize with. - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// Thrown when any error occurs during serialization. - public static void Serialize(IBufferWriter writer, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var fastWriter = new MessagePackWriter(writer) - { - CancellationToken = cancellationToken, - }; - Serialize(ref fastWriter, value, options); - fastWriter.Flush(); - } - - /// - /// Serializes a given value with the specified buffer writer. - /// - /// The buffer writer to serialize with. - /// The value to serialize. - /// The options. Use null to use default options. - /// Thrown when any error occurs during serialization. - public static void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options = null) - { - options = options ?? DefaultOptions; - bool originalOldSpecValue = writer.OldSpec; - if (options.OldSpec.HasValue) - { - writer.OldSpec = options.OldSpec.Value; - } - - try - { - if (options.Compression.IsCompression() && !PrimitiveChecker.IsMessagePackFixedSizePrimitive) - { - using (var scratchRental = SequencePool.Shared.Rent()) - { - var scratch = scratchRental.Value; - MessagePackWriter scratchWriter = writer.Clone(scratch); - options.Resolver.GetFormatterWithVerify().Serialize(ref scratchWriter, value, options); - scratchWriter.Flush(); - ToLZ4BinaryCore(scratch, ref writer, options.Compression); - } - } - else - { - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value, options); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException($"Failed to serialize {typeof(T).FullName} value.", ex); - } - finally - { - writer.OldSpec = originalOldSpecValue; - } - } - - /// - /// Serializes a given value with the specified buffer writer. - /// - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// A byte array with the serialized value. - /// Thrown when any error occurs during serialization. - public static byte[] Serialize(T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - byte[] array = scratchArray; - if (array == null) - { - scratchArray = array = new byte[65536]; - } - - var msgpackWriter = new MessagePackWriter(SequencePool.Shared, array) - { - CancellationToken = cancellationToken, - }; - Serialize(ref msgpackWriter, value, options); - return msgpackWriter.FlushAndGetArray(); - } - - /// - /// Serializes a given value to the specified stream. - /// - /// The stream to serialize to. - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// Thrown when any error occurs during serialization. - public static void Serialize(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent()) - { - Serialize(sequenceRental.Value, value, options, cancellationToken); - - try - { - foreach (ReadOnlyMemory segment in sequenceRental.Value.AsReadOnlySequence) - { - cancellationToken.ThrowIfCancellationRequested(); - stream.Write(segment.Span); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex); - } - } - } - - /// - /// Serializes a given value to the specified stream. - /// - /// The stream to serialize to. - /// The value to serialize. - /// The options. Use null to use default options. - /// A cancellation token. - /// A task that completes with the result of the async serialization operation. - /// Thrown when any error occurs during serialization. - public static async Task SerializeAsync(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent()) - { - Serialize(sequenceRental.Value, value, options, cancellationToken); - - try - { - foreach (ReadOnlyMemory segment in sequenceRental.Value.AsReadOnlySequence) - { - cancellationToken.ThrowIfCancellationRequested(); - await stream.WriteAsync(segment, cancellationToken).ConfigureAwait(false); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex); - } - } - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The sequence to deserialize from. - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(in ReadOnlySequence byteSequence, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var reader = new MessagePackReader(byteSequence) - { - CancellationToken = cancellationToken, - }; - return Deserialize(ref reader, options); - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The reader to deserialize from. - /// The options. Use null to use default options. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options = null) - { - options = options ?? DefaultOptions; - - try - { - if (options.Compression.IsCompression()) - { - using (var msgPackUncompressedRental = SequencePool.Shared.Rent()) - { - var msgPackUncompressed = msgPackUncompressedRental.Value; - if (TryDecompress(ref reader, msgPackUncompressed)) - { - MessagePackReader uncompressedReader = reader.Clone(msgPackUncompressed.AsReadOnlySequence); - return options.Resolver.GetFormatterWithVerify().Deserialize(ref uncompressedReader, options); - } - else - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - } - else - { - return options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - } - } - catch (Exception ex) - { - throw new MessagePackSerializationException($"Failed to deserialize {typeof(T).FullName} value.", ex); - } - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The buffer to deserialize from. - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ReadOnlyMemory buffer, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - var reader = new MessagePackReader(buffer) - { - CancellationToken = cancellationToken, - }; - return Deserialize(ref reader, options); - } - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The memory to deserialize from. - /// The number of bytes read. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ReadOnlyMemory buffer, out int bytesRead, CancellationToken cancellationToken = default) => Deserialize(buffer, options: null, out bytesRead, cancellationToken); - - /// - /// Deserializes a value of a given type from a sequence of bytes. - /// - /// The type of value to deserialize. - /// The memory to deserialize from. - /// The options. Use null to use default options. - /// The number of bytes read. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - public static T Deserialize(ReadOnlyMemory buffer, MessagePackSerializerOptions options, out int bytesRead, CancellationToken cancellationToken = default) - { - var reader = new MessagePackReader(buffer) - { - CancellationToken = cancellationToken, - }; - T result = Deserialize(ref reader, options); - bytesRead = buffer.Slice(0, (int)reader.Consumed).Length; - return result; - } - - /// - /// Deserializes the entire content of a . - /// - /// The type of value to deserialize. - /// - /// The stream to deserialize from. - /// The entire stream will be read, and the first msgpack token deserialized will be returned. - /// If is true on the stream, its position will be set to just after the last deserialized byte. - /// - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - /// - /// If multiple top-level msgpack data structures are expected on the stream, use instead. - /// - public static T Deserialize(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result)) - { - return result; - } - - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var sequence = sequenceRental.Value; - try - { - int bytesRead; - do - { - cancellationToken.ThrowIfCancellationRequested(); - Span span = sequence.GetSpan(stream.CanSeek ? (int)Math.Min(MaxHintSize, stream.Length - stream.Position) : 0); - bytesRead = stream.Read(span); - sequence.Advance(bytesRead); - } - while (bytesRead > 0); - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex); - } - - return DeserializeFromSequenceAndRewindStreamIfPossible(stream, options, sequence, cancellationToken); - } - } - - /// - /// Deserializes the entire content of a . - /// - /// The type of value to deserialize. - /// - /// The stream to deserialize from. - /// The entire stream will be read, and the first msgpack token deserialized will be returned. - /// If is true on the stream, its position will be set to just after the last deserialized byte. - /// - /// The options. Use null to use default options. - /// A cancellation token. - /// The deserialized value. - /// Thrown when any error occurs during deserialization. - /// - /// If multiple top-level msgpack data structures are expected on the stream, use instead. - /// - public static async ValueTask DeserializeAsync(Stream stream, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) - { - if (TryDeserializeFromMemoryStream(stream, options, cancellationToken, out T result)) - { - return result; - } - - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var sequence = sequenceRental.Value; - try - { - int bytesRead; - do - { - Memory memory = sequence.GetMemory(stream.CanSeek ? (int)Math.Min(MaxHintSize, stream.Length - stream.Position) : 0); - bytesRead = await stream.ReadAsync(memory, cancellationToken).ConfigureAwait(false); - sequence.Advance(bytesRead); - } - while (bytesRead > 0); - } - catch (Exception ex) - { - throw new MessagePackSerializationException("Error occurred while reading from the stream.", ex); - } - - return DeserializeFromSequenceAndRewindStreamIfPossible(stream, options, sequence, cancellationToken); - } - } - - private delegate int LZ4Transform(ReadOnlySpan input, Span output); - - private static readonly LZ4Transform LZ4CodecEncode = LZ4Codec.Encode; - private static readonly LZ4Transform LZ4CodecDecode = LZ4Codec.Decode; - - private static bool TryDeserializeFromMemoryStream(Stream stream, MessagePackSerializerOptions options, CancellationToken cancellationToken, out T result) - { - cancellationToken.ThrowIfCancellationRequested(); - if (stream is MemoryStream ms && ms.TryGetBuffer(out ArraySegment streamBuffer)) - { - result = Deserialize(streamBuffer.AsMemory(checked((int)ms.Position)), options, out int bytesRead, cancellationToken); - - // Emulate that we had actually "read" from the stream. - ms.Seek(bytesRead, SeekOrigin.Current); - return true; - } - - result = default; - return false; - } - - private static T DeserializeFromSequenceAndRewindStreamIfPossible(Stream streamToRewind, MessagePackSerializerOptions options, ReadOnlySequence sequence, CancellationToken cancellationToken) - { - if (streamToRewind is null) - { - throw new ArgumentNullException(nameof(streamToRewind)); - } - - var reader = new MessagePackReader(sequence) - { - CancellationToken = cancellationToken, - }; - T result = Deserialize(ref reader, options); - - if (streamToRewind.CanSeek && !reader.End) - { - // Reverse the stream as many bytes as we left unread. - int bytesNotRead = checked((int)reader.Sequence.Slice(reader.Position).Length); - streamToRewind.Seek(-bytesNotRead, SeekOrigin.Current); - } - - return result; - } - - /// - /// Performs LZ4 compression or decompression. - /// - /// The input for the operation. - /// The buffer to write the result of the operation. - /// The LZ4 codec transformation. - /// The number of bytes written to the . - private static int LZ4Operation(in ReadOnlySequence input, Span output, LZ4Transform lz4Operation) - { - ReadOnlySpan inputSpan; - byte[] rentedInputArray = null; - if (input.IsSingleSegment) - { - inputSpan = input.First.Span; - } - else - { - rentedInputArray = ArrayPool.Shared.Rent((int)input.Length); - input.CopyTo(rentedInputArray); - inputSpan = rentedInputArray.AsSpan(0, (int)input.Length); - } - - try - { - return lz4Operation(inputSpan, output); - } - finally - { - if (rentedInputArray != null) - { - ArrayPool.Shared.Return(rentedInputArray); - } - } - } - - private static bool TryDecompress(ref MessagePackReader reader, IBufferWriter writer) - { - if (!reader.End) - { - // Try to find LZ4Block - if (reader.NextMessagePackType == MessagePackType.Extension) - { - MessagePackReader peekReader = reader.CreatePeekReader(); - ExtensionHeader header = peekReader.ReadExtensionFormatHeader(); - if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4Block) - { - // Read the extension using the original reader, so we "consume" it. - ExtensionResult extension = reader.ReadExtensionFormat(); - var extReader = new MessagePackReader(extension.Data); - - // The first part of the extension payload is a MessagePack-encoded Int32 that - // tells us the length the data will be AFTER decompression. - int uncompressedLength = extReader.ReadInt32(); - - // The rest of the payload is the compressed data itself. - ReadOnlySequence compressedData = extReader.Sequence.Slice(extReader.Position); - - Span uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength); - int actualUncompressedLength = LZ4Operation(compressedData, uncompressedSpan, LZ4CodecDecode); - Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data."); - writer.Advance(actualUncompressedLength); - return true; - } - } - - // Try to find LZ4BlockArray - if (reader.NextMessagePackType == MessagePackType.Array) - { - MessagePackReader peekReader = reader.CreatePeekReader(); - var arrayLength = peekReader.ReadArrayHeader(); - if (arrayLength != 0 && peekReader.NextMessagePackType == MessagePackType.Extension) - { - ExtensionHeader header = peekReader.ReadExtensionFormatHeader(); - if (header.TypeCode == ThisLibraryExtensionTypeCodes.Lz4BlockArray) - { - // switch peekReader as original reader. - reader = peekReader; - - // Read from [Ext(98:int,int...), bin,bin,bin...] - var sequenceCount = arrayLength - 1; - var uncompressedLengths = ArrayPool.Shared.Rent(sequenceCount); - try - { - for (int i = 0; i < sequenceCount; i++) - { - uncompressedLengths[i] = reader.ReadInt32(); - } - - for (int i = 0; i < sequenceCount; i++) - { - var uncompressedLength = uncompressedLengths[i]; - var lz4Block = reader.ReadBytes(); - Span uncompressedSpan = writer.GetSpan(uncompressedLength).Slice(0, uncompressedLength); - var actualUncompressedLength = LZ4Operation(lz4Block.Value, uncompressedSpan, LZ4CodecDecode); - Debug.Assert(actualUncompressedLength == uncompressedLength, "Unexpected length of uncompressed data."); - writer.Advance(actualUncompressedLength); - } - - return true; - } - finally - { - ArrayPool.Shared.Return(uncompressedLengths); - } - } - } - } - } - - return false; - } - - private static void ToLZ4BinaryCore(in ReadOnlySequence msgpackUncompressedData, ref MessagePackWriter writer, MessagePackCompression compression) - { - if (compression == MessagePackCompression.Lz4Block) - { - if (msgpackUncompressedData.Length < LZ4NotCompressionSizeInLz4BlockType) - { - writer.WriteRaw(msgpackUncompressedData); - return; - } - - var maxCompressedLength = LZ4Codec.MaximumOutputLength((int)msgpackUncompressedData.Length); - var lz4Span = ArrayPool.Shared.Rent(maxCompressedLength); - try - { - int lz4Length = LZ4Operation(msgpackUncompressedData, lz4Span, LZ4CodecEncode); - - const int LengthOfUncompressedDataSizeHeader = 5; - writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4Block, LengthOfUncompressedDataSizeHeader + (uint)lz4Length)); - writer.WriteInt32((int)msgpackUncompressedData.Length); - writer.WriteRaw(lz4Span.AsSpan(0, lz4Length)); - } - finally - { - ArrayPool.Shared.Return(lz4Span); - } - } - else if (compression == MessagePackCompression.Lz4BlockArray) - { - // Write to [Ext(98:int,int...), bin,bin,bin...] - var sequenceCount = 0; - var extHeaderSize = 0; - foreach (var item in msgpackUncompressedData) - { - sequenceCount++; - extHeaderSize += GetUInt32WriteSize((uint)item.Length); - } - - writer.WriteArrayHeader(sequenceCount + 1); - writer.WriteExtensionFormatHeader(new ExtensionHeader(ThisLibraryExtensionTypeCodes.Lz4BlockArray, extHeaderSize)); - { - foreach (var item in msgpackUncompressedData) - { - writer.Write(item.Length); - } - } - - foreach (var item in msgpackUncompressedData) - { - var maxCompressedLength = LZ4Codec.MaximumOutputLength(item.Length); - var lz4Span = writer.GetSpan(maxCompressedLength + 5); - int lz4Length = LZ4Codec.Encode(item.Span, lz4Span.Slice(5, lz4Span.Length - 5)); - WriteBin32Header((uint)lz4Length, lz4Span); - writer.Advance(lz4Length + 5); - } - } - else - { - throw new ArgumentException("Invalid MessagePackCompression Code. Code:" + compression); - } - } - - private static int GetUInt32WriteSize(uint value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - return 1; - } - else if (value <= byte.MaxValue) - { - return 2; - } - else if (value <= ushort.MaxValue) - { - return 3; - } - else - { - return 5; - } - } - - private static void WriteBin32Header(uint value, Span span) - { - unchecked - { - span[0] = MessagePackCode.Bin32; - - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[4] = (byte)value; - span[3] = (byte)(value >> 8); - span[2] = (byte)(value >> 16); - span[1] = (byte)(value >> 24); - } - } - - private static class PrimitiveChecker - { - public static readonly bool IsMessagePackFixedSizePrimitive; - - static PrimitiveChecker() - { - IsMessagePackFixedSizePrimitive = IsMessagePackFixedSizePrimitiveTypeHelper(typeof(T)); - } - } - - private static bool IsMessagePackFixedSizePrimitiveTypeHelper(Type type) - { - return type == typeof(short) - || type == typeof(int) - || type == typeof(long) - || type == typeof(ushort) - || type == typeof(uint) - || type == typeof(ulong) - || type == typeof(float) - || type == typeof(double) - || type == typeof(bool) - || type == typeof(byte) - || type == typeof(sbyte) - || type == typeof(char) - ; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.cs.meta deleted file mode 100644 index 5129144..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d33e055ed9d0f484d9048fb29fa84ba3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializerOptions.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializerOptions.cs deleted file mode 100644 index 8eb9835..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializerOptions.cs +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; - -namespace MessagePack -{ -#if !DYNAMICCODEDUMPER - /// - /// An immutable description of options for running the . - /// -#endif - public class MessagePackSerializerOptions - { - // see:http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx - internal static readonly Regex AssemblyNameVersionSelectorRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=[\w-]+, PublicKeyToken=(?:null|[a-f0-9]{16})$", RegexOptions.Compiled); - - /// - /// A collection of known dangerous types that are not expected in a typical MessagePack stream, - /// and thus are rejected by the default implementation of . - /// - private static readonly HashSet DisallowedTypes = new HashSet - { - "System.CodeDom.Compiler.TempFileCollection", - "System.Management.IWbemClassObjectFreeThreaded", - }; - -#if !DYNAMICCODEDUMPER - /// - /// Gets a good default set of options that uses the and no compression. - /// - public static MessagePackSerializerOptions Standard => MessagePackSerializerOptionsDefaultSettingsLazyInitializationHelper.Standard; -#endif - - /// - /// Initializes a new instance of the class. - /// - protected internal MessagePackSerializerOptions(IFormatterResolver resolver) - { - this.Resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); - } - - /// - /// Initializes a new instance of the class - /// with members initialized from an existing instance. - /// - /// The options to copy from. - protected MessagePackSerializerOptions(MessagePackSerializerOptions copyFrom) - { - if (copyFrom == null) - { - throw new ArgumentNullException(nameof(copyFrom)); - } - - this.Resolver = copyFrom.Resolver; - this.Compression = copyFrom.Compression; - this.OldSpec = copyFrom.OldSpec; - this.OmitAssemblyVersion = copyFrom.OmitAssemblyVersion; - this.AllowAssemblyVersionMismatch = copyFrom.AllowAssemblyVersionMismatch; - this.Security = copyFrom.Security; - } - - /// - /// Gets the resolver to use for complex types. - /// - /// An instance of . Never null. - /// Thrown if an attempt is made to set this property to null. - public IFormatterResolver Resolver { get; private set; } - - /// - /// Gets the compression scheme to apply to serialized sequences. - /// - /// - /// When set to something other than , - /// deserialization can still work on uncompressed sequences, - /// and serialization may not compress if msgpack sequences are short enough that compression would not likely be advantageous. - /// - public MessagePackCompression Compression { get; private set; } - - /// - /// Gets a value indicating whether to serialize with set to some value - /// causing messagepack spec compliance to be explicitly set to the old or new format. - /// - /// - /// A null value means the 's default or previous setting will be used. - /// A non-null value will be applied to the property for the duration of a - /// serialization and then reverted to its prior setting. - /// - /// - /// Reading always supports both new and old spec. - /// - public bool? OldSpec { get; private set; } - - /// - /// Gets a value indicating whether serialization should omit assembly version, culture and public key token metadata when using the typeless formatter. - /// - /// The default value is false. - public bool OmitAssemblyVersion { get; private set; } - - /// - /// Gets a value indicating whether deserialization may instantiate types from an assembly with a different version if a matching version cannot be found. - /// - /// The default value is false. - public bool AllowAssemblyVersionMismatch { get; private set; } - - /// - /// Gets the security-related options for deserializing messagepack sequences. - /// - /// - /// The default value is to use . - /// - public MessagePackSecurity Security { get; private set; } = MessagePackSecurity.TrustedData; - - /// - /// Gets a type given a string representation of the type. - /// - /// The name of the type to load. This is typically the but may use the assembly's simple name. - /// The loaded type or null if no matching type could be found. - public virtual Type LoadType(string typeName) - { - Type result = Type.GetType(typeName, false); - if (result == null && this.AllowAssemblyVersionMismatch) - { - string shortenedName = AssemblyNameVersionSelectorRegex.Replace(typeName, string.Empty); - if (shortenedName != typeName) - { - result = Type.GetType(shortenedName, false); - } - } - - return result; - } - - /// - /// Checks whether a given type may be deserialized. - /// - /// The type to be instantiated. - /// Thrown if the is not allowed to be deserialized. - /// - /// This method provides a means for an important security mitigation when using the Typeless formatter to prevent untrusted messagepack from - /// deserializing objects that may be harmful if instantiated, disposed or finalized. - /// The default implementation throws for only a few known dangerous types. - /// Applications that deserialize from untrusted sources should override this method and throw if the type is not among the expected set. - /// - public virtual void ThrowIfDeserializingTypeIsDisallowed(Type type) - { - if (DisallowedTypes.Contains(type.FullName)) - { - throw new MessagePackSerializationException("Deserialization attempted to create the type " + type.FullName + " which is not allowed."); - } - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the . - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithResolver(IFormatterResolver resolver) - { - if (this.Resolver == resolver) - { - return this; - } - - var result = this.Clone(); - result.Resolver = resolver; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithCompression(MessagePackCompression compression) - { - if (this.Compression == compression) - { - return this; - } - - var result = this.Clone(); - result.Compression = compression; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the . - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithOldSpec(bool? oldSpec = true) - { - if (this.OldSpec == oldSpec) - { - return this; - } - - var result = this.Clone(); - result.OldSpec = oldSpec; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithOmitAssemblyVersion(bool omitAssemblyVersion) - { - if (this.OmitAssemblyVersion == omitAssemblyVersion) - { - return this; - } - - var result = this.Clone(); - result.OmitAssemblyVersion = omitAssemblyVersion; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithAllowAssemblyVersionMismatch(bool allowAssemblyVersionMismatch) - { - if (this.AllowAssemblyVersionMismatch == allowAssemblyVersionMismatch) - { - return this; - } - - var result = this.Clone(); - result.AllowAssemblyVersionMismatch = allowAssemblyVersionMismatch; - return result; - } - - /// - /// Gets a copy of these options with the property set to a new value. - /// - /// The new value for the property. - /// The new instance; or the original if the value is unchanged. - public MessagePackSerializerOptions WithSecurity(MessagePackSecurity security) - { - if (security is null) - { - throw new ArgumentNullException(nameof(security)); - } - - if (this.Security == security) - { - return this; - } - - var result = this.Clone(); - result.Security = security; - return result; - } - - /// - /// Creates a clone of this instance with the same properties set. - /// - /// The cloned instance. Guaranteed to be a new instance. - /// Thrown if this instance is a derived type that doesn't override this method. - protected virtual MessagePackSerializerOptions Clone() - { - if (this.GetType() != typeof(MessagePackSerializerOptions)) - { - throw new NotSupportedException($"The derived type {this.GetType().FullName} did not override the {nameof(Clone)} method as required."); - } - - return new MessagePackSerializerOptions(this); - } - -#if !DYNAMICCODEDUMPER - private static class MessagePackSerializerOptionsDefaultSettingsLazyInitializationHelper - { - public static readonly MessagePackSerializerOptions Standard = new MessagePackSerializerOptions(Resolvers.StandardResolver.Instance); - } -#endif - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializerOptions.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializerOptions.cs.meta deleted file mode 100644 index 9668470..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackSerializerOptions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 621e07593f75d314eb0388aa92ef6805 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackStreamReader.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackStreamReader.cs deleted file mode 100644 index fb439dd..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackStreamReader.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Nerdbank.Streams; - -namespace MessagePack -{ - /// - /// Reads one or more messagepack data structures from a . - /// - /// - /// This class is *not* thread-safe. Do not call more than one member at once and be sure any call completes (including asynchronous tasks) - /// before calling the next one. - /// - public partial class MessagePackStreamReader : IDisposable - { - private readonly Stream stream; - private readonly bool leaveOpen; - private SequencePool.Rental sequenceRental = SequencePool.Shared.Rent(); - private SequencePosition? endOfLastMessage; - - /// - /// Initializes a new instance of the class. - /// - /// The stream to read from. This stream will be disposed of when this is disposed. - public MessagePackStreamReader(Stream stream) - : this(stream, leaveOpen: false) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The stream to read from. - /// If true, leaves the stream open after this is disposed; otherwise, false. - public MessagePackStreamReader(Stream stream, bool leaveOpen) - { - this.stream = stream ?? throw new ArgumentNullException(nameof(stream)); - this.leaveOpen = leaveOpen; - } - - /// - /// Gets any bytes that have been read since the last complete message returned from . - /// - public ReadOnlySequence RemainingBytes => this.endOfLastMessage.HasValue ? this.ReadData.AsReadOnlySequence.Slice(this.endOfLastMessage.Value) : this.ReadData.AsReadOnlySequence; - - /// - /// Gets the sequence that we read data from the into. - /// - private Sequence ReadData => this.sequenceRental.Value; - - /// - /// Reads the next whole (top-level) messagepack data structure. - /// - /// A cancellation token. - /// - /// A task whose result is the next whole data structure from the stream, or null if the stream ends. - /// The returned sequence is valid until this is disposed or - /// until this method is called again, whichever comes first. - /// - /// - /// When null is the result of the returned task, - /// any extra bytes read (between the last complete message and the end of the stream) will be available via the property. - /// - public async ValueTask?> ReadAsync(CancellationToken cancellationToken) - { - this.RecycleLastMessage(); - - while (true) - { - // Check if we have a complete message and return it if we have it. - // We do this before reading anything since a previous read may have brought in several messages. - cancellationToken.ThrowIfCancellationRequested(); - if (this.TryReadNextMessage(out ReadOnlySequence completeMessage)) - { - return completeMessage; - } - - if (!await this.TryReadMoreDataAsync(cancellationToken).ConfigureAwait(false)) - { - // We've reached the end of the stream. - // We already checked for a complete message with what we already had, so evidently it's not a complete message. - return null; - } - } - } - - /// - /// Arranges for the next read operation to start by reading from the underlying - /// instead of any data buffered from a previous read. - /// - /// - /// This is appropriate if the underlying has been repositioned such that - /// any previously buffered data is no longer applicable to what the caller wants to read. - /// - public void DiscardBufferedData() - { - this.sequenceRental.Value.Reset(); - this.endOfLastMessage = default; - } - - /// - public void Dispose() - { - if (!this.leaveOpen) - { - this.stream.Dispose(); - } - - this.sequenceRental.Dispose(); - this.sequenceRental = default; - } - - /// - /// Recycle memory from a previously returned message. - /// - private void RecycleLastMessage() - { - if (this.endOfLastMessage.HasValue) - { - // A previously returned message can now be safely recycled since the caller wants more. - this.ReadData.AdvanceTo(this.endOfLastMessage.Value); - this.endOfLastMessage = null; - } - } - - /// - /// Read more data from the stream into the buffer. - /// - /// A cancellation token. - /// true if more data was read; false if the end of the stream had already been reached. - private async Task TryReadMoreDataAsync(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - Memory buffer = this.ReadData.GetMemory(sizeHint: 0); - int bytesRead = 0; - try - { - bytesRead = await this.stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); - return bytesRead > 0; - } - finally - { - // Keep our state clean in case the caller wants to call us again. - this.ReadData.Advance(bytesRead); - } - } - - /// - /// Checks whether the content in include a complete messagepack structure. - /// - /// Receives the sequence of the first complete data structure found, if any. - /// true if a complete data structure was found; false otherwise. - private bool TryReadNextMessage(out ReadOnlySequence completeMessage) - { - if (this.ReadData.Length > 0) - { - var reader = new MessagePackReader(this.ReadData); - - // Perf opportunity: instead of skipping from the start each time, we could incrementally skip across tries - // possibly as easy as simply keeping a count of how many tokens still need to be skipped (that we know about). - if (reader.TrySkip()) - { - this.endOfLastMessage = reader.Position; - completeMessage = reader.Sequence.Slice(0, reader.Position); - return true; - } - } - - completeMessage = default; - return false; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackStreamReader.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackStreamReader.cs.meta deleted file mode 100644 index b9b4f11..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackStreamReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 40b616b9ee299b04c97f5efb6c1cde9c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackWriter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackWriter.cs deleted file mode 100644 index 482bb41..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackWriter.cs +++ /dev/null @@ -1,1324 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading; -using MessagePack.Internal; -using Microsoft; - -namespace MessagePack -{ - /// - /// A primitive types writer for the MessagePack format. - /// - /// - /// The MessagePack spec.. - /// -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - ref struct MessagePackWriter - { - /// - /// The writer to use. - /// - private BufferWriter writer; - - /// - /// Initializes a new instance of the struct. - /// - /// The writer to use. - public MessagePackWriter(IBufferWriter writer) - : this() - { - this.writer = new BufferWriter(writer); - this.OldSpec = false; - } - - /// - /// Initializes a new instance of the struct. - /// - /// The pool from which to draw an if required.. - /// An array to start with so we can avoid accessing the if possible. - internal MessagePackWriter(SequencePool sequencePool, byte[] array) - : this() - { - this.writer = new BufferWriter(sequencePool, array); - this.OldSpec = false; - } - - /// - /// Gets or sets the cancellation token for this serialization operation. - /// - public CancellationToken CancellationToken { get; set; } - - /// - /// Gets or sets a value indicating whether to write in old spec compatibility mode. - /// - public bool OldSpec { get; set; } - - /// - /// Initializes a new instance of the struct, - /// with the same settings as this one, but with its own buffer writer. - /// - /// The writer to use for the new instance. - /// The new writer. - public MessagePackWriter Clone(IBufferWriter writer) => new MessagePackWriter(writer) - { - OldSpec = this.OldSpec, - CancellationToken = this.CancellationToken, - }; - - /// - /// Ensures everything previously written has been flushed to the underlying . - /// - public void Flush() => this.writer.Commit(); - - /// - /// Writes a value. - /// - public void WriteNil() - { - Span span = this.writer.GetSpan(1); - span[0] = MessagePackCode.Nil; - this.writer.Advance(1); - } - - /// - /// Copies bytes directly into the message pack writer. - /// - /// The span of bytes to copy from. - public void WriteRaw(ReadOnlySpan rawMessagePackBlock) => this.writer.Write(rawMessagePackBlock); - - /// - /// Copies bytes directly into the message pack writer. - /// - /// The span of bytes to copy from. - public void WriteRaw(in ReadOnlySequence rawMessagePackBlock) - { - foreach (ReadOnlyMemory segment in rawMessagePackBlock) - { - this.writer.Write(segment.Span); - } - } - - /// - /// Write the length of the next array to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of elements that will be written in the array. - public void WriteArrayHeader(int count) => this.WriteArrayHeader((uint)count); - - /// - /// Write the length of the next array to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of elements that will be written in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void WriteArrayHeader(uint count) - { - if (count <= MessagePackRange.MaxFixArrayCount) - { - Span span = this.writer.GetSpan(1); - span[0] = (byte)(MessagePackCode.MinFixArray | count); - this.writer.Advance(1); - } - else if (count <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Array16; - WriteBigEndian((ushort)count, span.Slice(1)); - this.writer.Advance(3); - } - else - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Array32; - WriteBigEndian(count, span.Slice(1)); - this.writer.Advance(5); - } - } - - /// - /// Write the length of the next map to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of key=value pairs that will be written in the map. - public void WriteMapHeader(int count) => this.WriteMapHeader((uint)count); - - /// - /// Write the length of the next map to be written in the most compact form of - /// , - /// , or - /// . - /// - /// The number of key=value pairs that will be written in the map. - public void WriteMapHeader(uint count) - { - if (count <= MessagePackRange.MaxFixMapCount) - { - Span span = this.writer.GetSpan(1); - span[0] = (byte)(MessagePackCode.MinFixMap | count); - this.writer.Advance(1); - } - else if (count <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Map16; - WriteBigEndian((ushort)count, span.Slice(1)); - this.writer.Advance(3); - } - else - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Map32; - WriteBigEndian(count, span.Slice(1)); - this.writer.Advance(5); - } - } - - /// - /// Writes a value using a 1-byte code when possible, otherwise as . - /// - /// The value. - public void Write(byte value) - { - if (value <= MessagePackCode.MaxFixInt) - { - Span span = this.writer.GetSpan(1); - span[0] = value; - this.writer.Advance(1); - } - else - { - this.WriteUInt8(value); - } - } - - /// - /// Writes a value using . - /// - /// The value. - public void WriteUInt8(byte value) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = value; - this.writer.Advance(2); - } - - /// - /// Writes an 8-bit value using a 1-byte code when possible, otherwise as . - /// - /// The value. - public void Write(sbyte value) - { - if (value < MessagePackRange.MinFixNegativeInt) - { - this.WriteInt8(value); - } - else - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - } - - /// - /// Writes an 8-bit value using . - /// - /// The value. - public void WriteInt8(sbyte value) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - - /// - /// Writes a value using a 1-byte code when possible, otherwise as or . - /// - /// The value. - public void Write(ushort value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value <= byte.MaxValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else - { - this.WriteUInt16(value); - } - } - - /// - /// Writes a value using . - /// - /// The value. - public void WriteUInt16(ushort value) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.UInt16; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(3); - } - - /// - /// Writes a using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , or - /// . - /// - /// The value to write. - public void Write(short value) - { - if (value >= 0) - { - this.Write((ushort)value); - } - else - { - // negative int(use int) - if (value >= MessagePackRange.MinFixNegativeInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value >= sbyte.MinValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else - { - this.WriteInt16(value); - } - } - } - - /// - /// Writes a using . - /// - /// The value to write. - public void WriteInt16(short value) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Int16; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(3); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , or - /// . - /// - /// The value to write. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(uint value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value <= byte.MaxValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.UInt16; - WriteBigEndian((ushort)value, span.Slice(1)); - this.writer.Advance(3); - } - else - { - this.WriteUInt32(value); - } - } - - /// - /// Writes an using . - /// - /// The value to write. - public void WriteUInt32(uint value) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.UInt32; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(5); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , - /// , - /// , - /// . - /// - /// The value to write. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Write(int value) - { - if (value >= 0) - { - this.Write((uint)value); - } - else - { - // negative int(use int) - if (value >= MessagePackRange.MinFixNegativeInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value >= sbyte.MinValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value >= short.MinValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Int16; - WriteBigEndian((short)value, span.Slice(1)); - this.writer.Advance(3); - } - else - { - this.WriteInt32(value); - } - } - } - - /// - /// Writes an using . - /// - /// The value to write. - public void WriteInt32(int value) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Int32; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(5); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , - /// , - /// , - /// . - /// - /// The value to write. - public void Write(ulong value) - { - if (value <= MessagePackRange.MaxFixPositiveInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value <= byte.MaxValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.UInt8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.UInt16; - WriteBigEndian((ushort)value, span.Slice(1)); - this.writer.Advance(3); - } - else if (value <= uint.MaxValue) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.UInt32; - WriteBigEndian((uint)value, span.Slice(1)); - this.writer.Advance(5); - } - else - { - this.WriteUInt64(value); - } - } - - /// - /// Writes an using . - /// - /// The value to write. - public void WriteUInt64(ulong value) - { - Span span = this.writer.GetSpan(9); - span[0] = MessagePackCode.UInt64; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(9); - } - - /// - /// Writes an using a built-in 1-byte code when within specific MessagePack-supported ranges, - /// or the most compact of - /// , - /// , - /// , - /// , - /// , - /// , - /// , - /// . - /// - /// The value to write. - public void Write(long value) - { - if (value >= 0) - { - this.Write((ulong)value); - } - else - { - // negative int(use int) - if (value >= MessagePackRange.MinFixNegativeInt) - { - Span span = this.writer.GetSpan(1); - span[0] = unchecked((byte)value); - this.writer.Advance(1); - } - else if (value >= sbyte.MinValue) - { - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.Int8; - span[1] = unchecked((byte)value); - this.writer.Advance(2); - } - else if (value >= short.MinValue) - { - Span span = this.writer.GetSpan(3); - span[0] = MessagePackCode.Int16; - WriteBigEndian((short)value, span.Slice(1)); - this.writer.Advance(3); - } - else if (value >= int.MinValue) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Int32; - WriteBigEndian((int)value, span.Slice(1)); - this.writer.Advance(5); - } - else - { - this.WriteInt64(value); - } - } - } - - /// - /// Writes a using . - /// - /// The value to write. - public void WriteInt64(long value) - { - Span span = this.writer.GetSpan(9); - span[0] = MessagePackCode.Int64; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(9); - } - - /// - /// Writes a value using either or . - /// - /// The value. - public void Write(bool value) - { - Span span = this.writer.GetSpan(1); - span[0] = value ? MessagePackCode.True : MessagePackCode.False; - this.writer.Advance(1); - } - - /// - /// Writes a value using a 1-byte code when possible, otherwise as or . - /// - /// The value. - public void Write(char value) => this.Write((ushort)value); - - /// - /// Writes a value. - /// - /// The value. - public void Write(float value) - { - Span span = this.writer.GetSpan(5); - span[0] = MessagePackCode.Float32; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(5); - } - - /// - /// Writes a value. - /// - /// The value. - public void Write(double value) - { - Span span = this.writer.GetSpan(9); - span[0] = MessagePackCode.Float64; - WriteBigEndian(value, span.Slice(1)); - this.writer.Advance(9); - } - - /// - /// Writes a using the message code . - /// - /// The value to write. - /// Thrown when is true because the old spec does not define a format. - public void Write(DateTime dateTime) - { - if (this.OldSpec) - { - throw new NotSupportedException($"The MsgPack spec does not define a format for {nameof(DateTime)} in {nameof(this.OldSpec)} mode. Turn off {nameof(this.OldSpec)} mode or use NativeDateTimeFormatter."); - } - else - { - // Timestamp spec - // https://github.com/msgpack/msgpack/pull/209 - // FixExt4(-1) => seconds | [1970-01-01 00:00:00 UTC, 2106-02-07 06:28:16 UTC) range - // FixExt8(-1) => nanoseconds + seconds | [1970-01-01 00:00:00.000000000 UTC, 2514-05-30 01:53:04.000000000 UTC) range - // Ext8(12,-1) => nanoseconds + seconds | [-584554047284-02-23 16:59:44 UTC, 584554051223-11-09 07:00:16.000000000 UTC) range - - // The spec requires UTC. Convert to UTC if we're sure the value was expressed as Local time. - // If it's Unspecified, we want to leave it alone since .NET will change the value when we convert - // and we simply don't know, so we should leave it as-is. - if (dateTime.Kind == DateTimeKind.Local) - { - dateTime = dateTime.ToUniversalTime(); - } - - var secondsSinceBclEpoch = dateTime.Ticks / TimeSpan.TicksPerSecond; - var seconds = secondsSinceBclEpoch - DateTimeConstants.BclSecondsAtUnixEpoch; - var nanoseconds = (dateTime.Ticks % TimeSpan.TicksPerSecond) * DateTimeConstants.NanosecondsPerTick; - - // reference pseudo code. - /* - struct timespec { - long tv_sec; // seconds - long tv_nsec; // nanoseconds - } time; - if ((time.tv_sec >> 34) == 0) - { - uint64_t data64 = (time.tv_nsec << 34) | time.tv_sec; - if (data & 0xffffffff00000000L == 0) - { - // timestamp 32 - uint32_t data32 = data64; - serialize(0xd6, -1, data32) - } - else - { - // timestamp 64 - serialize(0xd7, -1, data64) - } - } - else - { - // timestamp 96 - serialize(0xc7, 12, -1, time.tv_nsec, time.tv_sec) - } - */ - - if ((seconds >> 34) == 0) - { - var data64 = unchecked((ulong)((nanoseconds << 34) | seconds)); - if ((data64 & 0xffffffff00000000L) == 0) - { - // timestamp 32(seconds in 32-bit unsigned int) - var data32 = (UInt32)data64; - Span span = this.writer.GetSpan(6); - span[0] = MessagePackCode.FixExt4; - span[1] = unchecked((byte)ReservedMessagePackExtensionTypeCode.DateTime); - WriteBigEndian(data32, span.Slice(2)); - this.writer.Advance(6); - } - else - { - // timestamp 64(nanoseconds in 30-bit unsigned int | seconds in 34-bit unsigned int) - Span span = this.writer.GetSpan(10); - span[0] = MessagePackCode.FixExt8; - span[1] = unchecked((byte)ReservedMessagePackExtensionTypeCode.DateTime); - WriteBigEndian(data64, span.Slice(2)); - this.writer.Advance(10); - } - } - else - { - // timestamp 96( nanoseconds in 32-bit unsigned int | seconds in 64-bit signed int ) - Span span = this.writer.GetSpan(15); - span[0] = MessagePackCode.Ext8; - span[1] = 12; - span[2] = unchecked((byte)ReservedMessagePackExtensionTypeCode.DateTime); - WriteBigEndian((uint)nanoseconds, span.Slice(3)); - WriteBigEndian(seconds, span.Slice(7)); - this.writer.Advance(15); - } - } - } - - /// - /// Writes a [], prefixed with a length encoded as the smallest fitting from: - /// , - /// , - /// , - /// or if is null. - /// - /// The array of bytes to write. May be null. - public void Write(byte[] src) - { - if (src == null) - { - this.WriteNil(); - } - else - { - this.Write(src.AsSpan()); - } - } - - /// - /// Writes a span of bytes, prefixed with a length encoded as the smallest fitting from: - /// , - /// , or - /// . - /// - /// The span of bytes to write. - /// - /// When is true, the msgpack code used is , or instead. - /// - public void Write(ReadOnlySpan src) - { - int length = (int)src.Length; - this.WriteBinHeader(length); - var span = this.writer.GetSpan(length); - src.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes a sequence of bytes, prefixed with a length encoded as the smallest fitting from: - /// , - /// , or - /// . - /// - /// The span of bytes to write. - /// - /// When is true, the msgpack code used is , or instead. - /// - public void Write(in ReadOnlySequence src) - { - int length = (int)src.Length; - this.WriteBinHeader(length); - var span = this.writer.GetSpan(length); - src.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes the header that precedes a raw binary sequence with a length encoded as the smallest fitting from: - /// , - /// , or - /// . - /// - /// The length of bytes that will be written next. - /// - /// - /// The caller should use or - /// after calling this method to actually write the content. - /// Alternatively a single call to or will take care of the header and content in one call. - /// - /// - /// When is true, the msgpack code used is , or instead. - /// - /// - public void WriteBinHeader(int length) - { - if (this.OldSpec) - { - this.WriteStringHeader(length); - return; - } - - // When we write the header, we'll ask for all the space we need for the payload as well - // as that may help ensure we only allocate a buffer once. - if (length <= byte.MaxValue) - { - var size = length + 2; - Span span = this.writer.GetSpan(size); - - span[0] = MessagePackCode.Bin8; - span[1] = (byte)length; - - this.writer.Advance(2); - } - else if (length <= UInt16.MaxValue) - { - var size = length + 3; - Span span = this.writer.GetSpan(size); - - span[0] = MessagePackCode.Bin16; - WriteBigEndian((ushort)length, span.Slice(1)); - - this.writer.Advance(3); - } - else - { - var size = length + 5; - Span span = this.writer.GetSpan(size); - - span[0] = MessagePackCode.Bin32; - WriteBigEndian(length, span.Slice(1)); - - this.writer.Advance(5); - } - } - - /// - /// Writes out an array of bytes that (may) represent a UTF-8 encoded string, prefixed with the length using one of these message codes: - /// , - /// , - /// , or - /// . - /// - /// The bytes to write. - public void WriteString(in ReadOnlySequence utf8stringBytes) - { - var length = (int)utf8stringBytes.Length; - this.WriteStringHeader(length); - Span span = this.writer.GetSpan(length); - utf8stringBytes.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes out an array of bytes that (may) represent a UTF-8 encoded string, prefixed with the length using one of these message codes: - /// , - /// , - /// , or - /// . - /// - /// The bytes to write. - public void WriteString(ReadOnlySpan utf8stringBytes) - { - var length = utf8stringBytes.Length; - this.WriteStringHeader(length); - Span span = this.writer.GetSpan(length); - utf8stringBytes.CopyTo(span); - this.writer.Advance(length); - } - - /// - /// Writes out the header that may precede a UTF-8 encoded string, prefixed with the length using one of these message codes: - /// , - /// , - /// , or - /// . - /// - /// The number of bytes in the string that will follow this header. - /// - /// The caller should use or - /// after calling this method to actually write the content. - /// Alternatively a single call to or will take care of the header and content in one call. - /// - public void WriteStringHeader(int byteCount) - { - // When we write the header, we'll ask for all the space we need for the payload as well - // as that may help ensure we only allocate a buffer once. - if (byteCount <= MessagePackRange.MaxFixStringLength) - { - Span span = this.writer.GetSpan(byteCount + 1); - span[0] = (byte)(MessagePackCode.MinFixStr | byteCount); - this.writer.Advance(1); - } - else if (byteCount <= byte.MaxValue && !this.OldSpec) - { - Span span = this.writer.GetSpan(byteCount + 2); - span[0] = MessagePackCode.Str8; - span[1] = unchecked((byte)byteCount); - this.writer.Advance(2); - } - else if (byteCount <= ushort.MaxValue) - { - Span span = this.writer.GetSpan(byteCount + 3); - span[0] = MessagePackCode.Str16; - WriteBigEndian((ushort)byteCount, span.Slice(1)); - this.writer.Advance(3); - } - else - { - Span span = this.writer.GetSpan(byteCount + 5); - span[0] = MessagePackCode.Str32; - WriteBigEndian(byteCount, span.Slice(1)); - this.writer.Advance(5); - } - } - - /// - /// Writes out a , prefixed with the length using one of these message codes: - /// , - /// , - /// , - /// , - /// or if the is null. - /// - /// The value to write. May be null. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public unsafe void Write(string value) - { - if (value == null) - { - this.WriteNil(); - return; - } - - ref byte buffer = ref this.WriteString_PrepareSpan(value.Length, out int bufferSize, out int useOffset); - fixed (char* pValue = value) - fixed (byte* pBuffer = &buffer) - { - int byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize); - this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); - } - } - - /// - /// Writes out a , prefixed with the length using one of these message codes: - /// , - /// , - /// , - /// . - /// - /// The value to write. - public unsafe void Write(ReadOnlySpan value) - { - ref byte buffer = ref this.WriteString_PrepareSpan(value.Length, out int bufferSize, out int useOffset); - fixed (char* pValue = value) - fixed (byte* pBuffer = &buffer) - { - int byteCount = StringEncoding.UTF8.GetBytes(pValue, value.Length, pBuffer + useOffset, bufferSize); - this.WriteString_PostEncoding(pBuffer, useOffset, byteCount); - } - } - - /// - /// Writes the extension format header, using the smallest one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// The extension header. - public void WriteExtensionFormatHeader(ExtensionHeader extensionHeader) - { - int dataLength = (int)extensionHeader.Length; - byte typeCode = unchecked((byte)extensionHeader.TypeCode); - switch (dataLength) - { - case 1: - Span span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt1; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 2: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt2; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 4: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt4; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 8: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt8; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - case 16: - span = this.writer.GetSpan(2); - span[0] = MessagePackCode.FixExt16; - span[1] = unchecked(typeCode); - this.writer.Advance(2); - return; - default: - unchecked - { - if (dataLength <= byte.MaxValue) - { - span = this.writer.GetSpan(dataLength + 3); - span[0] = MessagePackCode.Ext8; - span[1] = unchecked((byte)dataLength); - span[2] = unchecked(typeCode); - this.writer.Advance(3); - } - else if (dataLength <= UInt16.MaxValue) - { - span = this.writer.GetSpan(dataLength + 4); - span[0] = MessagePackCode.Ext16; - WriteBigEndian((ushort)dataLength, span.Slice(1)); - span[3] = unchecked(typeCode); - this.writer.Advance(4); - } - else - { - span = this.writer.GetSpan(dataLength + 6); - span[0] = MessagePackCode.Ext32; - WriteBigEndian(dataLength, span.Slice(1)); - span[5] = unchecked(typeCode); - this.writer.Advance(6); - } - } - - break; - } - } - - /// - /// Writes an extension format, using the smallest one of these codes: - /// , - /// , - /// , - /// , - /// , - /// , - /// , or - /// . - /// - /// The extension data. - public void WriteExtensionFormat(ExtensionResult extensionData) - { - this.WriteExtensionFormatHeader(extensionData.Header); - this.WriteRaw(extensionData.Data); - } - - /// - /// Gets memory where raw messagepack data can be written. - /// - /// The size of the memory block required. - /// The span of memory to write to. This *may* exceed . - /// - /// After initializing the resulting memory, always follow up with a call to . - /// - /// This is similar in purpose to - /// but provides uninitialized memory for the caller to write to instead of copying initialized memory from elsewhere. - /// - /// - /// - public Span GetSpan(int length) => this.writer.GetSpan(length); - - /// - /// Commits memory previously returned from as initialized. - /// - /// The number of bytes initialized with messagepack data from the previously returned span. - /// - public void Advance(int length) => this.writer.Advance(length); - - /// - /// Writes a 16-bit integer in big endian format. - /// - /// The integer. - internal void WriteBigEndian(ushort value) - { - Span span = this.writer.GetSpan(2); - WriteBigEndian(value, span); - this.writer.Advance(2); - } - - /// - /// Writes a 32-bit integer in big endian format. - /// - /// The integer. - internal void WriteBigEndian(uint value) - { - Span span = this.writer.GetSpan(4); - WriteBigEndian(value, span); - this.writer.Advance(4); - } - - /// - /// Writes a 64-bit integer in big endian format. - /// - /// The integer. - internal void WriteBigEndian(ulong value) - { - Span span = this.writer.GetSpan(8); - WriteBigEndian(value, span); - this.writer.Advance(8); - } - - internal byte[] FlushAndGetArray() - { - if (this.writer.TryGetUncommittedSpan(out ReadOnlySpan span)) - { - return span.ToArray(); - } - else - { - if (this.writer.SequenceRental.Value == null) - { - throw new NotSupportedException("This instance was not initialized to support this operation."); - } - - this.Flush(); - byte[] result = this.writer.SequenceRental.Value.AsReadOnlySequence.ToArray(); - this.writer.SequenceRental.Dispose(); - return result; - } - } - - private static void WriteBigEndian(short value, Span span) => WriteBigEndian(unchecked((ushort)value), span); - - private static void WriteBigEndian(int value, Span span) => WriteBigEndian(unchecked((uint)value), span); - - private static void WriteBigEndian(long value, Span span) => WriteBigEndian(unchecked((ulong)value), span); - - private static void WriteBigEndian(ushort value, Span span) - { - unchecked - { - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[1] = (byte)value; - span[0] = (byte)(value >> 8); - } - } - - private static unsafe void WriteBigEndian(ushort value, byte* span) - { - unchecked - { - span[0] = (byte)(value >> 8); - span[1] = (byte)value; - } - } - - private static void WriteBigEndian(uint value, Span span) - { - unchecked - { - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[3] = (byte)value; - span[2] = (byte)(value >> 8); - span[1] = (byte)(value >> 16); - span[0] = (byte)(value >> 24); - } - } - - private static unsafe void WriteBigEndian(uint value, byte* span) - { - unchecked - { - span[0] = (byte)(value >> 24); - span[1] = (byte)(value >> 16); - span[2] = (byte)(value >> 8); - span[3] = (byte)value; - } - } - - private static void WriteBigEndian(ulong value, Span span) - { - unchecked - { - // Write to highest index first so the JIT skips bounds checks on subsequent writes. - span[7] = (byte)value; - span[6] = (byte)(value >> 8); - span[5] = (byte)(value >> 16); - span[4] = (byte)(value >> 24); - span[3] = (byte)(value >> 32); - span[2] = (byte)(value >> 40); - span[1] = (byte)(value >> 48); - span[0] = (byte)(value >> 56); - } - } - - private static unsafe void WriteBigEndian(float value, Span span) => WriteBigEndian(*(int*)&value, span); - - private static unsafe void WriteBigEndian(double value, Span span) => WriteBigEndian(*(long*)&value, span); - - /// - /// Estimates the length of the header required for a given string. - /// - /// The length of the string to be written, in characters. - /// Receives the guaranteed length of the returned buffer. - /// Receives the offset within the returned buffer to write the encoded string to. - /// - /// A reference to the first byte in the buffer. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private ref byte WriteString_PrepareSpan(int characterLength, out int bufferSize, out int encodedBytesOffset) - { - // MaxByteCount -> WritePrefix -> GetBytes has some overheads of `MaxByteCount` - // solves heuristic length check - - // ensure buffer by MaxByteCount(faster than GetByteCount) - bufferSize = StringEncoding.UTF8.GetMaxByteCount(characterLength) + 5; - ref byte buffer = ref this.writer.GetPointer(bufferSize); - - int useOffset; - if (characterLength <= MessagePackRange.MaxFixStringLength) - { - useOffset = 1; - } - else if (characterLength <= byte.MaxValue && !this.OldSpec) - { - useOffset = 2; - } - else if (characterLength <= ushort.MaxValue) - { - useOffset = 3; - } - else - { - useOffset = 5; - } - - encodedBytesOffset = useOffset; - return ref buffer; - } - - /// - /// Finalizes an encoding of a string. - /// - /// A pointer obtained from a prior call to . - /// The offset obtained from a prior call to . - /// The number of bytes used to actually encode the string. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private unsafe void WriteString_PostEncoding(byte* pBuffer, int estimatedOffset, int byteCount) - { - // move body and write prefix - if (byteCount <= MessagePackRange.MaxFixStringLength) - { - if (estimatedOffset != 1) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 1, byteCount, byteCount); - } - - pBuffer[0] = (byte)(MessagePackCode.MinFixStr | byteCount); - this.writer.Advance(byteCount + 1); - } - else if (byteCount <= byte.MaxValue && !this.OldSpec) - { - if (estimatedOffset != 2) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 2, byteCount, byteCount); - } - - pBuffer[0] = MessagePackCode.Str8; - pBuffer[1] = unchecked((byte)byteCount); - this.writer.Advance(byteCount + 2); - } - else if (byteCount <= ushort.MaxValue) - { - if (estimatedOffset != 3) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 3, byteCount, byteCount); - } - - pBuffer[0] = MessagePackCode.Str16; - WriteBigEndian((ushort)byteCount, pBuffer + 1); - this.writer.Advance(byteCount + 3); - } - else - { - if (estimatedOffset != 5) - { - MemoryCopy(pBuffer + estimatedOffset, pBuffer + 5, byteCount, byteCount); - } - - pBuffer[0] = MessagePackCode.Str32; - WriteBigEndian((uint)byteCount, pBuffer + 1); - this.writer.Advance(byteCount + 5); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) - { -#pragma warning disable 0162 - - if (Utilities.IsMono) - { - // mono does not guarantee overlapped memcpy so for Unity and NETSTANDARD use slow path. - // https://github.com/neuecc/MessagePack-CSharp/issues/562 - var buffer = ArrayPool.Shared.Rent((int)sourceBytesToCopy); - try - { - fixed (byte* p = buffer) - { - Buffer.MemoryCopy(source, p, sourceBytesToCopy, sourceBytesToCopy); - Buffer.MemoryCopy(p, destination, destinationSizeInBytes, sourceBytesToCopy); - } - } - finally - { - ArrayPool.Shared.Return(buffer); - } - } - else - { - Buffer.MemoryCopy(source, destination, destinationSizeInBytes, sourceBytesToCopy); - } - -#pragma warning restore 0162 - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackWriter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackWriter.cs.meta deleted file mode 100644 index 58afe29..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MessagePackWriter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a22e47d7013792844bd7882f11f25e1d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MonoProtection.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MonoProtection.cs deleted file mode 100644 index 42bf1f8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MonoProtection.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Threading; - -namespace MessagePack -{ - /// - /// Special behavior for running on the mono runtime. - /// - internal struct MonoProtection - { - /// - /// Gets a value indicating whether the mono runtime is executing this code. - /// - internal static bool IsRunningOnMono => Type.GetType("Mono.Runtime") != null; - - /// - /// A lock that we enter on mono when generating dynamic types. - /// - private static readonly object RefEmitLock = new object(); - - /// - /// The method to call within the expression of a using statement whose block surrounds all Ref.Emit code. - /// - /// The value to be disposed of to exit the Ref.Emit lock. - /// - /// This is a no-op except when running on Mono. - /// Mono's implementation of Ref.Emit is not thread-safe so we have to lock around all use of it - /// when using that runtime. - /// - internal static MonoProtectionDisposal EnterRefEmitLock() => IsRunningOnMono ? new MonoProtectionDisposal(RefEmitLock) : default; - } - - internal struct MonoProtectionDisposal : IDisposable - { - private readonly object lockObject; - - internal MonoProtectionDisposal(object lockObject) - { - this.lockObject = lockObject; - Monitor.Enter(lockObject); - } - - public void Dispose() - { - if (this.lockObject is object) - { - Monitor.Exit(this.lockObject); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MonoProtection.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MonoProtection.cs.meta deleted file mode 100644 index 604658b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/MonoProtection.cs.meta +++ /dev/null @@ -1,10 +0,0 @@ -guid: 593f3b742b875ea48943776d02f8d3a9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Nil.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Nil.cs deleted file mode 100644 index 9533d24..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Nil.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -namespace MessagePack -{ -#if MESSAGEPACK_INTERNAL - internal -#else - public -#endif - struct Nil : IEquatable - { - public static readonly Nil Default = default(Nil); - - public override bool Equals(object obj) - { - return obj is Nil; - } - - public bool Equals(Nil other) - { - return true; - } - - public override int GetHashCode() - { - return 0; - } - - public override string ToString() - { - return "()"; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Nil.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Nil.cs.meta deleted file mode 100644 index 48551eb..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Nil.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f5ce64c07ab69e449bdf3e4144c199dd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers.meta deleted file mode 100644 index 607dfce..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 432f67d3d1e83554686cf89a82aaa5f9 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/AttributeFormatterResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/AttributeFormatterResolver.cs deleted file mode 100644 index 00e5b07..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/AttributeFormatterResolver.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Linq; // require UNITY_2018_3_OR_NEWER -using System.Reflection; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - /// - /// Get formatter from . - /// - public sealed class AttributeFormatterResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly AttributeFormatterResolver Instance = new AttributeFormatterResolver(); - - private AttributeFormatterResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { -#if UNITY_2018_3_OR_NEWER && !NETFX_CORE - var attr = (MessagePackFormatterAttribute)typeof(T).GetCustomAttributes(typeof(MessagePackFormatterAttribute), true).FirstOrDefault(); -#else - MessagePackFormatterAttribute attr = typeof(T).GetTypeInfo().GetCustomAttribute(); -#endif - if (attr == null) - { - return; - } - - var formatterType = attr.FormatterType; - if (formatterType.IsGenericType && !formatterType.IsConstructedGenericType) - { - formatterType = formatterType.MakeGenericType(typeof(T).GetGenericArguments()); - } - - if (attr.Arguments == null) - { - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterType); - } - else - { - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterType, attr.Arguments); - } - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/AttributeFormatterResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/AttributeFormatterResolver.cs.meta deleted file mode 100644 index 9c3844b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/AttributeFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c02a22f37aeb19147a0a91b233f75622 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/BuiltinResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/BuiltinResolver.cs deleted file mode 100644 index 8d03163..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/BuiltinResolver.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using MessagePack.Formatters; -using MessagePack.Internal; -using MessagePack.Resolvers; - -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1509 // Opening braces should not be preceded by blank line - -namespace MessagePack.Resolvers -{ - public sealed class BuiltinResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly BuiltinResolver Instance = new BuiltinResolver(); - - private BuiltinResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - // Reduce IL2CPP code generate size(don't write long code in ) - Formatter = (IMessagePackFormatter)BuiltinResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class BuiltinResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - // Primitive - { typeof(Int16), Int16Formatter.Instance }, - { typeof(Int32), Int32Formatter.Instance }, - { typeof(Int64), Int64Formatter.Instance }, - { typeof(UInt16), UInt16Formatter.Instance }, - { typeof(UInt32), UInt32Formatter.Instance }, - { typeof(UInt64), UInt64Formatter.Instance }, - { typeof(Single), SingleFormatter.Instance }, - { typeof(Double), DoubleFormatter.Instance }, - { typeof(bool), BooleanFormatter.Instance }, - { typeof(byte), ByteFormatter.Instance }, - { typeof(sbyte), SByteFormatter.Instance }, - { typeof(DateTime), DateTimeFormatter.Instance }, - { typeof(char), CharFormatter.Instance }, - - // Nulllable Primitive - { typeof(Int16?), NullableInt16Formatter.Instance }, - { typeof(Int32?), NullableInt32Formatter.Instance }, - { typeof(Int64?), NullableInt64Formatter.Instance }, - { typeof(UInt16?), NullableUInt16Formatter.Instance }, - { typeof(UInt32?), NullableUInt32Formatter.Instance }, - { typeof(UInt64?), NullableUInt64Formatter.Instance }, - { typeof(Single?), NullableSingleFormatter.Instance }, - { typeof(Double?), NullableDoubleFormatter.Instance }, - { typeof(bool?), NullableBooleanFormatter.Instance }, - { typeof(byte?), NullableByteFormatter.Instance }, - { typeof(sbyte?), NullableSByteFormatter.Instance }, - { typeof(DateTime?), NullableDateTimeFormatter.Instance }, - { typeof(char?), NullableCharFormatter.Instance }, - - // StandardClassLibraryFormatter - { typeof(string), NullableStringFormatter.Instance }, - { typeof(decimal), DecimalFormatter.Instance }, - { typeof(decimal?), new StaticNullableFormatter(DecimalFormatter.Instance) }, - { typeof(TimeSpan), TimeSpanFormatter.Instance }, - { typeof(TimeSpan?), new StaticNullableFormatter(TimeSpanFormatter.Instance) }, - { typeof(DateTimeOffset), DateTimeOffsetFormatter.Instance }, - { typeof(DateTimeOffset?), new StaticNullableFormatter(DateTimeOffsetFormatter.Instance) }, - { typeof(Guid), GuidFormatter.Instance }, - { typeof(Guid?), new StaticNullableFormatter(GuidFormatter.Instance) }, - { typeof(Uri), UriFormatter.Instance }, - { typeof(Version), VersionFormatter.Instance }, - { typeof(StringBuilder), StringBuilderFormatter.Instance }, - { typeof(BitArray), BitArrayFormatter.Instance }, - { typeof(Type), TypeFormatter.Instance }, - - // special primitive - { typeof(byte[]), ByteArrayFormatter.Instance }, - - // Nil - { typeof(Nil), NilFormatter.Instance }, - { typeof(Nil?), NullableNilFormatter.Instance }, - - // optimized primitive array formatter - { typeof(Int16[]), Int16ArrayFormatter.Instance }, - { typeof(Int32[]), Int32ArrayFormatter.Instance }, - { typeof(Int64[]), Int64ArrayFormatter.Instance }, - { typeof(UInt16[]), UInt16ArrayFormatter.Instance }, - { typeof(UInt32[]), UInt32ArrayFormatter.Instance }, - { typeof(UInt64[]), UInt64ArrayFormatter.Instance }, - { typeof(Single[]), SingleArrayFormatter.Instance }, - { typeof(Double[]), DoubleArrayFormatter.Instance }, - { typeof(Boolean[]), BooleanArrayFormatter.Instance }, - { typeof(SByte[]), SByteArrayFormatter.Instance }, - { typeof(DateTime[]), DateTimeArrayFormatter.Instance }, - { typeof(Char[]), CharArrayFormatter.Instance }, - { typeof(string[]), NullableStringArrayFormatter.Instance }, - - // well known collections - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - - { typeof(object[]), new ArrayFormatter() }, - { typeof(List), new ListFormatter() }, - - { typeof(Memory), ByteMemoryFormatter.Instance }, - { typeof(Memory?), new StaticNullableFormatter>(ByteMemoryFormatter.Instance) }, - { typeof(ReadOnlyMemory), ByteReadOnlyMemoryFormatter.Instance }, - { typeof(ReadOnlyMemory?), new StaticNullableFormatter>(ByteReadOnlyMemoryFormatter.Instance) }, - { typeof(ReadOnlySequence), ByteReadOnlySequenceFormatter.Instance }, - { typeof(ReadOnlySequence?), new StaticNullableFormatter>(ByteReadOnlySequenceFormatter.Instance) }, - { typeof(ArraySegment), ByteArraySegmentFormatter.Instance }, - { typeof(ArraySegment?), new StaticNullableFormatter>(ByteArraySegmentFormatter.Instance) }, - - { typeof(System.Numerics.BigInteger), BigIntegerFormatter.Instance }, - { typeof(System.Numerics.BigInteger?), new StaticNullableFormatter(BigIntegerFormatter.Instance) }, - { typeof(System.Numerics.Complex), ComplexFormatter.Instance }, - { typeof(System.Numerics.Complex?), new StaticNullableFormatter(ComplexFormatter.Instance) }, - }; - - internal static object GetFormatter(Type t) - { - object formatter; - if (FormatterMap.TryGetValue(t, out formatter)) - { - return formatter; - } - - if (typeof(Type).IsAssignableFrom(t)) - { - return typeof(TypeFormatter<>).MakeGenericType(t).GetField(nameof(TypeFormatter.Instance)).GetValue(null); - } - - return null; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/BuiltinResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/BuiltinResolver.cs.meta deleted file mode 100644 index caee02f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/BuiltinResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8576a58290a3c2f4b856a090338fe4e3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs deleted file mode 100644 index 4f69183..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// A base class for classes that want to cache their responses for perf reasons. - /// - internal abstract class CachingFormatterResolver : IFormatterResolver - { - /// - /// The cache of types to their formatters. - /// - private readonly ThreadsafeTypeKeyHashTable formatters = new ThreadsafeTypeKeyHashTable(); - - /// - public IMessagePackFormatter GetFormatter() - { - if (!this.formatters.TryGetValue(typeof(T), out IMessagePackFormatter formatter)) - { - formatter = this.GetFormatterCore(); - this.formatters.TryAdd(typeof(T), formatter); - } - - return (IMessagePackFormatter)formatter; - } - - /// - /// Looks up a formatter for a type that has not been previously cached. - /// - /// The type to be formatted. - /// The formatter to use, or null if none found. - protected abstract IMessagePackFormatter GetFormatterCore(); - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs.meta deleted file mode 100644 index b1f6961..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CachingFormatterResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0b890291dfa50d64eb8a47edaeae5a2e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CompositeResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CompositeResolver.cs deleted file mode 100644 index daec235..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CompositeResolver.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// Represents a collection of formatters and resolvers acting as one. - /// - /// - /// This class is not thread-safe for mutations. It is thread-safe when not being written to. - /// - public static class CompositeResolver - { - private static readonly ReadOnlyDictionary EmptyFormattersByType = new ReadOnlyDictionary(new Dictionary()); - - /// - /// Initializes a new instance of an with the specified formatters and sub-resolvers. - /// - /// - /// A list of instances of to prefer (above the ). - /// The formatters are searched in the order given, so if two formatters support serializing the same type, the first one is used. - /// May not be null, but may be . - /// - /// - /// A list of resolvers to use for serializing types for which does not include a formatter. - /// The resolvers are searched in the order given, so if two resolvers support serializing the same type, the first one is used. - /// May not be null, but may be . - /// - /// - /// An instance of . - /// - public static IFormatterResolver Create(IReadOnlyList formatters, IReadOnlyList resolvers) - { - if (formatters is null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (resolvers is null) - { - throw new ArgumentNullException(nameof(resolvers)); - } - - // Make a copy of the resolvers list provided by the caller to guard against them changing it later. - var immutableFormatters = formatters.ToArray(); - var immutableResolvers = resolvers.ToArray(); - - return new CachingResolver(immutableFormatters, immutableResolvers); - } - - public static IFormatterResolver Create(params IFormatterResolver[] resolvers) => Create(Array.Empty(), resolvers); - - public static IFormatterResolver Create(params IMessagePackFormatter[] formatters) => Create(formatters, Array.Empty()); - - private class CachingResolver : IFormatterResolver - { - private readonly ThreadsafeTypeKeyHashTable formattersCache = new ThreadsafeTypeKeyHashTable(); - private readonly IMessagePackFormatter[] subFormatters; - private readonly IFormatterResolver[] subResolvers; - - /// - /// Initializes a new instance of the class. - /// - internal CachingResolver(IMessagePackFormatter[] subFormatters, IFormatterResolver[] subResolvers) - { - this.subFormatters = subFormatters ?? throw new ArgumentNullException(nameof(subFormatters)); - this.subResolvers = subResolvers ?? throw new ArgumentNullException(nameof(subResolvers)); - } - - public IMessagePackFormatter GetFormatter() - { - if (!this.formattersCache.TryGetValue(typeof(T), out IMessagePackFormatter formatter)) - { - foreach (var subFormatter in this.subFormatters) - { - if (subFormatter is IMessagePackFormatter) - { - formatter = subFormatter; - goto CACHE; - } - } - - foreach (IFormatterResolver resolver in this.subResolvers) - { - formatter = resolver.GetFormatter(); - if (formatter != null) - { - goto CACHE; - } - } - -// when not found, cache null. -CACHE: - this.formattersCache.TryAdd(typeof(T), formatter); - } - - return (IMessagePackFormatter)formatter; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CompositeResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CompositeResolver.cs.meta deleted file mode 100644 index a7cc191..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/CompositeResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 855ae905af3dec6449d0ced09b158a43 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs deleted file mode 100644 index 04b9e5e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Text; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - // MEMO: Not completely implemented. - - ////public static class ContractlessReflectionObjectResolver - ////{ - //// // TODO:CamelCase Option? AllowPrivate? - //// public static readonly IFormatterResolver Default = new DefaultResolver(); - //// public static readonly IFormatterResolver Contractless = new ContractlessResolver(); - //// public static readonly IFormatterResolver ContractlessForceStringKey = new ContractlessForceStringResolver(); - - //// class DefaultResolver : IFormatterResolver - //// { - //// const bool ForceStringKey = false; - //// const bool Contractless = false; - //// const bool AllowPrivate = false; - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return Cache.formatter; - //// } - - //// static class Cache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static Cache() - //// { - //// var metaInfo = ObjectSerializationInfo.CreateOrNull(typeof(T), ForceStringKey, Contractless, AllowPrivate); - //// if (metaInfo != null) - //// { - //// formatter = new ReflectionObjectFormatter(metaInfo); - //// } - //// } - //// } - //// } - - //// class ContractlessResolver : IFormatterResolver - //// { - //// const bool ForceStringKey = false; - //// const bool Contractless = true; - //// const bool AllowPrivate = false; - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return Cache.formatter; - //// } - - //// static class Cache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static Cache() - //// { - //// var metaInfo = ObjectSerializationInfo.CreateOrNull(typeof(T), ForceStringKey, Contractless, AllowPrivate); - //// if (metaInfo != null) - //// { - //// formatter = new ReflectionObjectFormatter(metaInfo); - //// } - //// } - //// } - //// } - - //// class ContractlessForceStringResolver : IFormatterResolver - //// { - //// const bool ForceStringKey = true; - //// const bool Contractless = true; - //// const bool AllowPrivate = false; - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return Cache.formatter; - //// } - - //// static class Cache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static Cache() - //// { - //// var metaInfo = ObjectSerializationInfo.CreateOrNull(typeof(T), ForceStringKey, Contractless, AllowPrivate); - //// if (metaInfo != null) - //// { - //// formatter = new ReflectionObjectFormatter(metaInfo); - //// } - //// } - //// } - //// } - - ////} - - ////public class ReflectionObjectFormatter : IMessagePackFormatter - ////{ - //// readonly ObjectSerializationInfo metaInfo; - - //// // for write - //// readonly byte[][] writeMemberNames; - //// readonly ObjectSerializationInfo.EmittableMember[] writeMembers; - - //// // for read - //// readonly int[] constructorParameterIndexes; - //// readonly AutomataDictionary mapMemberDictionary; - //// readonly ObjectSerializationInfo.EmittableMember[] readMembers; - - //// internal ReflectionObjectFormatter(ObjectSerializationInfo metaInfo) - //// { - //// this.metaInfo = metaInfo; - - //// // for write - //// { - //// var memberNameList = new List(metaInfo.Members.Length); - //// var emmitableMemberList = new List(metaInfo.Members.Length); - //// foreach (var item in metaInfo.Members) - //// { - //// if (item.IsWritable) - //// { - //// emmitableMemberList.Add(item); - //// memberNameList.Add(Encoding.UTF8.GetBytes(item.Name)); - //// } - //// } - //// this.writeMemberNames = memberNameList.ToArray(); - //// this.writeMembers = emmitableMemberList.ToArray(); - //// } - //// // for read - //// { - //// var automata = new AutomataDictionary(); - //// var emmitableMemberList = new List(metaInfo.Members.Length); - //// int index = 0; - //// foreach (var item in metaInfo.Members) - //// { - //// if (item.IsReadable) - //// { - //// emmitableMemberList.Add(item); - //// automata.Add(item.Name, index++); - //// } - //// } - //// this.readMembers = emmitableMemberList.ToArray(); - //// this.mapMemberDictionary = automata; - //// } - //// } - - //// public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - //// { - //// // reduce generic method size, avoid write code in type. - //// if (metaInfo.IsIntKey) - //// { - //// return ReflectionObjectFormatterHelper.WriteArraySerialize(metaInfo, writeMembers, ref bytes, offset, value, formatterResolver); - //// } - //// else - //// { - //// return ReflectionObjectFormatterHelper.WriteMapSerialize(metaInfo, writeMembers, writeMemberNames, ref bytes, offset, value, formatterResolver); - //// } - //// } - - //// public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - //// { - //// return (T)ReflectionObjectFormatterHelper.Deserialize(metaInfo, readMembers, constructorParameterIndexes, mapMemberDictionary, bytes, offset, formatterResolver, out readSize); - //// } - ////} - - ////internal static class ReflectionObjectFormatterHelper - ////{ - //// internal static int WriteArraySerialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] writeMembers, ref byte[] bytes, int offset, object value, IFormatterResolver formatterResolver) - //// { - //// var startOffset = offset; - - //// offset += MessagePackBinary.WriteArrayHeader(ref bytes, offset, writeMembers.Length); - //// foreach (var item in metaInfo.Members) - //// { - //// if (item == null) - //// { - //// offset += MessagePackBinary.WriteNil(ref bytes, offset); - //// } - //// else - //// { - //// var memberValue = item.ReflectionLoadValue(value); - //// offset += MessagePackSerializer.NonGeneric.Serialize(item.Type, ref bytes, offset, memberValue, formatterResolver); - //// } - //// } - - //// return offset - startOffset; - //// } - - //// internal static int WriteMapSerialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] writeMembers, byte[][] memberNames, ref byte[] bytes, int offset, object value, IFormatterResolver formatterResolver) - //// { - //// var startOffset = offset; - - //// offset += MessagePackBinary.WriteMapHeader(ref bytes, offset, writeMembers.Length); - - //// for (int i = 0; i < writeMembers.Length; i++) - //// { - //// offset += MessagePackBinary.WriteStringBytes(ref bytes, offset, memberNames[i]); - //// var memberValue = writeMembers[i].ReflectionLoadValue(value); - //// offset += MessagePackSerializer.NonGeneric.Serialize(writeMembers[i].Type, ref bytes, offset, memberValue, formatterResolver); - //// } - - //// return offset - startOffset; - //// } - - //// internal static object Deserialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] readMembers, int[] constructorParameterIndexes, AutomataDictionary mapMemberDictionary, byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize) - //// { - //// var startOffset = offset; - //// object[] parameters = null; - - //// var headerType = MessagePackBinary.GetMessagePackType(bytes, offset); - //// if (headerType == MessagePackType.Nil) - //// { - //// readSize = 1; - //// return null; - //// } - //// else if (headerType == MessagePackType.Array) - //// { - //// var arraySize = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize); - //// offset += readSize; - - //// // ReadValues - //// parameters = new object[arraySize]; - //// for (int i = 0; i < arraySize; i++) - //// { - //// var info = readMembers[i]; - //// if (info != null) - //// { - //// parameters[i] = MessagePackSerializer.NonGeneric.Deserialize(info.Type, bytes, offset, formatterResolver, out readSize); - //// offset += readSize; - //// } - //// else - //// { - //// offset += MessagePackBinary.ReadNextBlock(bytes, offset); - //// } - //// } - //// } - //// else if (headerType == MessagePackType.Map) - //// { - //// var mapSize = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize); - //// offset += readSize; - - //// // ReadValues - //// parameters = new object[mapSize]; - //// for (int i = 0; i < mapSize; i++) - //// { - //// var rawPropName = MessagePackBinary.ReadStringSegment(bytes, offset, out readSize); - //// offset += readSize; - - //// int index; - //// if (mapMemberDictionary.TryGetValue(rawPropName.Array, rawPropName.Offset, rawPropName.Count, out index)) - //// { - //// var info = readMembers[index]; - //// parameters[index] = MessagePackSerializer.NonGeneric.Deserialize(info.Type, bytes, offset, formatterResolver, out readSize); - //// offset += readSize; - //// } - //// else - //// { - //// offset += MessagePackBinary.ReadNextBlock(bytes, offset); - //// } - //// } - //// } - //// else - //// { - //// throw new MessagePackSerializationException("Invalid MessagePackType:" + MessagePackCode.ToFormatName(bytes[offset])); - //// } - - //// // CreateObject - //// object result = null; - //// if (constructorParameterIndexes.Length == 0) - //// { - //// result = Activator.CreateInstance(metaInfo.Type); - //// } - //// else - //// { - //// var args = new object[constructorParameterIndexes.Length]; - //// for (int i = 0; i < constructorParameterIndexes.Length; i++) - //// { - //// args[i] = parameters[constructorParameterIndexes[i]]; - //// } - - //// result = Activator.CreateInstance(metaInfo.Type, args); - //// } - - //// // SetMembers - //// for (int i = 0; i < readMembers.Length; i++) - //// { - //// var info = readMembers[i]; - //// if (info != null) - //// { - //// info.ReflectionStoreValue(result, parameters[i]); - //// } - //// } - - //// readSize = offset - startOffset; - //// return result; - //// } - ////} -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs.meta deleted file mode 100644 index 1bd4f91..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ContractlessReflectionObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e632f1a629022ed4daaff789f1209a31 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs deleted file mode 100644 index f31bb2a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Reflection; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - public sealed class DynamicEnumAsStringResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicEnumAsStringResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static DynamicEnumAsStringResolver() - { - Instance = new DynamicEnumAsStringResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private DynamicEnumAsStringResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsNullable()) - { - // build underlying type and use wrapped formatter. - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - if (!ti.IsEnum) - { - return; - } - - var innerFormatter = DynamicEnumAsStringResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - else if (!ti.IsEnum) - { - return; - } - - Formatter = (IMessagePackFormatter)(object)new EnumAsStringFormatter(); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs.meta deleted file mode 100644 index f1f7d1b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumAsStringResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ceb07c86c3c5d534195759fcd8983804 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumResolver.cs deleted file mode 100644 index 63667bb..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumResolver.cs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Buffers; -using System.Reflection; -using System.Reflection.Emit; -using System.Threading; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// EnumResolver by dynamic code generation, serialized underlying type. - /// - public sealed class DynamicEnumResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicEnumResolver Instance = new DynamicEnumResolver(); - - private const string ModuleName = "MessagePack.Resolvers.DynamicEnumResolver"; - - private static readonly Lazy DynamicAssembly; - - private static int nameSequence = 0; - - private DynamicEnumResolver() - { - } - - static DynamicEnumResolver() - { - DynamicAssembly = new Lazy(() => new DynamicAssembly(ModuleName)); - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Value.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - if (ti.IsNullable()) - { - // build underlying type and use wrapped formatter. - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - if (!ti.IsEnum) - { - return; - } - - var innerFormatter = DynamicEnumResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - else if (!ti.IsEnum) - { - return; - } - - TypeInfo formatterTypeInfo = BuildType(typeof(T)); - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - - private static TypeInfo BuildType(Type enumType) - { - Type underlyingType = Enum.GetUnderlyingType(enumType); - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(enumType); - - using (MonoProtection.EnterRefEmitLock()) - { - TypeBuilder typeBuilder = DynamicAssembly.Value.DefineType("MessagePack.Formatters." + enumType.FullName.Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - - // void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - { - MethodBuilder method = typeBuilder.DefineMethod( - "Serialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - null, - new Type[] { typeof(MessagePackWriter).MakeByRefType(), enumType, typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ldarg_2); - il.Emit(OpCodes.Call, typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { underlyingType })); - il.Emit(OpCodes.Ret); - } - - // T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); - { - MethodBuilder method = typeBuilder.DefineMethod( - "Deserialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - enumType, - new Type[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Call, typeof(MessagePackReader).GetRuntimeMethod("Read" + underlyingType.Name, Type.EmptyTypes)); - il.Emit(OpCodes.Ret); - } - - return typeBuilder.CreateTypeInfo(); - } - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumResolver.cs.meta deleted file mode 100644 index fe9657f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicEnumResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4100353110cfb7040b2fa50beb2390ad -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicGenericResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicGenericResolver.cs deleted file mode 100644 index bb55524..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicGenericResolver.cs +++ /dev/null @@ -1,333 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - public sealed class DynamicGenericResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicGenericResolver Instance = new DynamicGenericResolver(); - - private DynamicGenericResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)DynamicGenericResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class DynamicGenericResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(List<>), typeof(ListFormatter<>) }, - { typeof(LinkedList<>), typeof(LinkedListFormatter<>) }, - { typeof(Queue<>), typeof(QueueFormatter<>) }, - { typeof(Stack<>), typeof(StackFormatter<>) }, - { typeof(HashSet<>), typeof(HashSetFormatter<>) }, - { typeof(ReadOnlyCollection<>), typeof(ReadOnlyCollectionFormatter<>) }, - { typeof(IList<>), typeof(InterfaceListFormatter2<>) }, - { typeof(ICollection<>), typeof(InterfaceCollectionFormatter2<>) }, - { typeof(IEnumerable<>), typeof(InterfaceEnumerableFormatter<>) }, - { typeof(Dictionary<,>), typeof(DictionaryFormatter<,>) }, - { typeof(IDictionary<,>), typeof(InterfaceDictionaryFormatter<,>) }, - { typeof(SortedDictionary<,>), typeof(SortedDictionaryFormatter<,>) }, - { typeof(SortedList<,>), typeof(SortedListFormatter<,>) }, - { typeof(ILookup<,>), typeof(InterfaceLookupFormatter<,>) }, - { typeof(IGrouping<,>), typeof(InterfaceGroupingFormatter<,>) }, - { typeof(ObservableCollection<>), typeof(ObservableCollectionFormatter<>) }, - { typeof(ReadOnlyObservableCollection<>), typeof(ReadOnlyObservableCollectionFormatter<>) }, - { typeof(IReadOnlyList<>), typeof(InterfaceReadOnlyListFormatter<>) }, - { typeof(IReadOnlyCollection<>), typeof(InterfaceReadOnlyCollectionFormatter<>) }, - { typeof(ISet<>), typeof(InterfaceSetFormatter<>) }, - { typeof(System.Collections.Concurrent.ConcurrentBag<>), typeof(ConcurrentBagFormatter<>) }, - { typeof(System.Collections.Concurrent.ConcurrentQueue<>), typeof(ConcurrentQueueFormatter<>) }, - { typeof(System.Collections.Concurrent.ConcurrentStack<>), typeof(ConcurrentStackFormatter<>) }, - { typeof(ReadOnlyDictionary<,>), typeof(ReadOnlyDictionaryFormatter<,>) }, - { typeof(IReadOnlyDictionary<,>), typeof(InterfaceReadOnlyDictionaryFormatter<,>) }, - { typeof(System.Collections.Concurrent.ConcurrentDictionary<,>), typeof(ConcurrentDictionaryFormatter<,>) }, - { typeof(Lazy<>), typeof(LazyFormatter<>) }, - }; - - // Reduce IL2CPP code generate size(don't write long code in ) - internal static object GetFormatter(Type t) - { - TypeInfo ti = t.GetTypeInfo(); - - if (t.IsArray) - { - var rank = t.GetArrayRank(); - if (rank == 1) - { - if (t.GetElementType() == typeof(byte)) - { - // byte[] is also supported in builtin formatter. - return ByteArrayFormatter.Instance; - } - - return Activator.CreateInstance(typeof(ArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else if (rank == 2) - { - return Activator.CreateInstance(typeof(TwoDimensionalArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else if (rank == 3) - { - return Activator.CreateInstance(typeof(ThreeDimensionalArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else if (rank == 4) - { - return Activator.CreateInstance(typeof(FourDimensionalArrayFormatter<>).MakeGenericType(t.GetElementType())); - } - else - { - return null; // not supported built-in - } - } - else if (ti.IsGenericType) - { - Type genericType = ti.GetGenericTypeDefinition(); - TypeInfo genericTypeInfo = genericType.GetTypeInfo(); - var isNullable = genericTypeInfo.IsNullable(); - Type nullableElementType = isNullable ? ti.GenericTypeArguments[0] : null; - - if (genericType == typeof(KeyValuePair<,>)) - { - return CreateInstance(typeof(KeyValuePairFormatter<,>), ti.GenericTypeArguments); - } - - // Tuple - else if (ti.FullName.StartsWith("System.Tuple")) - { - Type tupleFormatterType = null; - switch (ti.GenericTypeArguments.Length) - { - case 1: - tupleFormatterType = typeof(TupleFormatter<>); - break; - case 2: - tupleFormatterType = typeof(TupleFormatter<,>); - break; - case 3: - tupleFormatterType = typeof(TupleFormatter<,,>); - break; - case 4: - tupleFormatterType = typeof(TupleFormatter<,,,>); - break; - case 5: - tupleFormatterType = typeof(TupleFormatter<,,,,>); - break; - case 6: - tupleFormatterType = typeof(TupleFormatter<,,,,,>); - break; - case 7: - tupleFormatterType = typeof(TupleFormatter<,,,,,,>); - break; - case 8: - tupleFormatterType = typeof(TupleFormatter<,,,,,,,>); - break; - default: - break; - } - - return CreateInstance(tupleFormatterType, ti.GenericTypeArguments); - } - - // ValueTuple - else if (ti.FullName.StartsWith("System.ValueTuple")) - { - Type tupleFormatterType = null; - switch (ti.GenericTypeArguments.Length) - { - case 1: - tupleFormatterType = typeof(ValueTupleFormatter<>); - break; - case 2: - tupleFormatterType = typeof(ValueTupleFormatter<,>); - break; - case 3: - tupleFormatterType = typeof(ValueTupleFormatter<,,>); - break; - case 4: - tupleFormatterType = typeof(ValueTupleFormatter<,,,>); - break; - case 5: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,>); - break; - case 6: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,,>); - break; - case 7: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,,,>); - break; - case 8: - tupleFormatterType = typeof(ValueTupleFormatter<,,,,,,,>); - break; - default: - break; - } - - return CreateInstance(tupleFormatterType, ti.GenericTypeArguments); - } - - // ArraySegment - else if (genericType == typeof(ArraySegment<>)) - { - if (ti.GenericTypeArguments[0] == typeof(byte)) - { - return ByteArraySegmentFormatter.Instance; - } - else - { - return CreateInstance(typeof(ArraySegmentFormatter<>), ti.GenericTypeArguments); - } - } - - // Memory - else if (genericType == typeof(Memory<>)) - { - if (ti.GenericTypeArguments[0] == typeof(byte)) - { - return ByteMemoryFormatter.Instance; - } - else - { - return CreateInstance(typeof(MemoryFormatter<>), ti.GenericTypeArguments); - } - } - - // ReadOnlyMemory - else if (genericType == typeof(ReadOnlyMemory<>)) - { - if (ti.GenericTypeArguments[0] == typeof(byte)) - { - return ByteReadOnlyMemoryFormatter.Instance; - } - else - { - return CreateInstance(typeof(ReadOnlyMemoryFormatter<>), ti.GenericTypeArguments); - } - } - - // ReadOnlySequence - else if (genericType == typeof(ReadOnlySequence<>)) - { - if (ti.GenericTypeArguments[0] == typeof(byte)) - { - return ByteReadOnlySequenceFormatter.Instance; - } - else - { - return CreateInstance(typeof(ReadOnlySequenceFormatter<>), ti.GenericTypeArguments); - } - } - - // Standard Nullable - else if (isNullable) - { - return CreateInstance(typeof(NullableFormatter<>), new[] { nullableElementType }); - } - - // Mapped formatter - else - { - Type formatterType; - if (FormatterMap.TryGetValue(genericType, out formatterType)) - { - return CreateInstance(formatterType, ti.GenericTypeArguments); - } - } - } - else if (ti.IsEnum) - { - return CreateInstance(typeof(GenericEnumFormatter<>), new[] { t }); - } - else - { - // NonGeneric Collection - if (t == typeof(IEnumerable)) - { - return NonGenericInterfaceEnumerableFormatter.Instance; - } - else if (t == typeof(ICollection)) - { - return NonGenericInterfaceCollectionFormatter.Instance; - } - else if (t == typeof(IList)) - { - return NonGenericInterfaceListFormatter.Instance; - } - else if (t == typeof(IDictionary)) - { - return NonGenericInterfaceDictionaryFormatter.Instance; - } - - if (typeof(IList).GetTypeInfo().IsAssignableFrom(ti) && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - return Activator.CreateInstance(typeof(NonGenericListFormatter<>).MakeGenericType(t)); - } - else if (typeof(IDictionary).GetTypeInfo().IsAssignableFrom(ti) && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - return Activator.CreateInstance(typeof(NonGenericDictionaryFormatter<>).MakeGenericType(t)); - } - } - - // check inherited types(e.g. Foo : ICollection<>, Bar : ICollection) - { - // generic dictionary - var dictionaryDef = ti.ImplementedInterfaces.FirstOrDefault(x => x.GetTypeInfo().IsConstructedGenericType() && x.GetGenericTypeDefinition() == typeof(IDictionary<,>)); - if (dictionaryDef != null && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - Type keyType = dictionaryDef.GenericTypeArguments[0]; - Type valueType = dictionaryDef.GenericTypeArguments[1]; - return CreateInstance(typeof(GenericDictionaryFormatter<,,>), new[] { keyType, valueType, t }); - } - - // generic collection - var collectionDef = ti.ImplementedInterfaces.FirstOrDefault(x => x.GetTypeInfo().IsConstructedGenericType() && x.GetGenericTypeDefinition() == typeof(ICollection<>)); - if (collectionDef != null && ti.DeclaredConstructors.Any(x => x.GetParameters().Length == 0)) - { - Type elemType = collectionDef.GenericTypeArguments[0]; - return CreateInstance(typeof(GenericCollectionFormatter<,>), new[] { elemType, t }); - } - } - - return null; - } - - private static object CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments) - { - return Activator.CreateInstance(genericType.MakeGenericType(genericTypeArguments), arguments); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicGenericResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicGenericResolver.cs.meta deleted file mode 100644 index 618c65e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicGenericResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a246239c22950a44bb5bffdb3b388dd2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs deleted file mode 100644 index f285082..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs +++ /dev/null @@ -1,2155 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.Serialization; -using System.Text.RegularExpressions; -using System.Threading; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - /// - /// ObjectResolver by dynamic code generation. - /// - public sealed class DynamicObjectResolver : IFormatterResolver - { - private const string ModuleName = "MessagePack.Resolvers.DynamicObjectResolver"; - - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicObjectResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - internal static readonly Lazy DynamicAssembly; - - static DynamicObjectResolver() - { - Instance = new DynamicObjectResolver(); - Options = new MessagePackSerializerOptions(Instance); - DynamicAssembly = new Lazy(() => new DynamicAssembly(ModuleName)); - } - - private DynamicObjectResolver() - { - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Value.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface || ti.IsAbstract) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicObjectResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - return; - } - - TypeInfo formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), false, false); - if (formatterTypeInfo == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - } - - /// - /// ObjectResolver by dynamic code generation, allow private member. - /// - public sealed class DynamicObjectResolverAllowPrivate : IFormatterResolver - { - public static readonly DynamicObjectResolverAllowPrivate Instance = new DynamicObjectResolverAllowPrivate(); - - private DynamicObjectResolverAllowPrivate() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface || ti.IsAbstract) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicObjectResolverAllowPrivate.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - } - else - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), false, false, true); - } - } - } - } - - /// - /// ObjectResolver by dynamic code generation, no needs MessagePackObject attribute and serialized key as string. - /// - public sealed class DynamicContractlessObjectResolver : IFormatterResolver - { - public static readonly DynamicContractlessObjectResolver Instance = new DynamicContractlessObjectResolver(); - - private const string ModuleName = "MessagePack.Resolvers.DynamicContractlessObjectResolver"; - - private static readonly Lazy DynamicAssembly; - - private DynamicContractlessObjectResolver() - { - } - - static DynamicContractlessObjectResolver() - { - DynamicAssembly = new Lazy(() => new DynamicAssembly(ModuleName)); - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Value.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - return; - } - - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface || ti.IsAbstract) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicContractlessObjectResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - return; - } - - TypeInfo formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), true, true); - if (formatterTypeInfo == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - } - - /// - /// ObjectResolver by dynamic code generation, no needs MessagePackObject attribute and serialized key as string, allow private member. - /// - public sealed class DynamicContractlessObjectResolverAllowPrivate : IFormatterResolver - { - public static readonly DynamicContractlessObjectResolverAllowPrivate Instance = new DynamicContractlessObjectResolverAllowPrivate(); - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - return; - } - - TypeInfo ti = typeof(T).GetTypeInfo(); - - if (ti.IsInterface || ti.IsAbstract) - { - return; - } - - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicContractlessObjectResolverAllowPrivate.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - if (ti.IsAnonymous()) - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); - } - else - { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, true); - } - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class DynamicObjectTypeBuilder - { -#if !UNITY_2018_3_OR_NEWER - private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+", RegexOptions.Compiled); -#else - static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+"); -#endif - - private static int nameSequence = 0; - - private static HashSet ignoreTypes = new HashSet - { - { typeof(object) }, - { typeof(short) }, - { typeof(int) }, - { typeof(long) }, - { typeof(ushort) }, - { typeof(uint) }, - { typeof(ulong) }, - { typeof(float) }, - { typeof(double) }, - { typeof(bool) }, - { typeof(byte) }, - { typeof(sbyte) }, - { typeof(decimal) }, - { typeof(char) }, - { typeof(string) }, - { typeof(System.Guid) }, - { typeof(System.TimeSpan) }, - { typeof(System.DateTime) }, - { typeof(System.DateTimeOffset) }, - { typeof(MessagePack.Nil) }, - }; - - public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool forceStringKey, bool contractless) - { - if (ignoreTypes.Contains(type)) - { - return null; - } - - var serializationInfo = MessagePack.Internal.ObjectSerializationInfo.CreateOrNull(type, forceStringKey, contractless, false); - if (serializationInfo == null) - { - return null; - } - - if (!(type.IsPublic || type.IsNestedPublic)) - { - throw new MessagePackSerializationException("Building dynamic formatter only allows public type. Type: " + type.FullName); - } - - using (MonoProtection.EnterRefEmitLock()) - { - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - TypeBuilder typeBuilder = assembly.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - - FieldBuilder stringByteKeysField = null; - Dictionary customFormatterLookup = null; - - // string key needs string->int mapper for deserialize switch statement - if (serializationInfo.IsStringKey) - { - ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); - stringByteKeysField = typeBuilder.DefineField("stringByteKeys", typeof(byte[][]), FieldAttributes.Private | FieldAttributes.InitOnly); - - ILGenerator il = method.GetILGenerator(); - BuildConstructor(type, serializationInfo, method, stringByteKeysField, il); - customFormatterLookup = BuildCustomFormatterField(typeBuilder, serializationInfo, il); - il.Emit(OpCodes.Ret); - } - else - { - ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); - ILGenerator il = method.GetILGenerator(); - il.EmitLoadThis(); - il.Emit(OpCodes.Call, objectCtor); - customFormatterLookup = BuildCustomFormatterField(typeBuilder, serializationInfo, il); - il.Emit(OpCodes.Ret); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Serialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - returnType: null, - parameterTypes: new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - method.DefineParameter(1, ParameterAttributes.None, "writer"); - method.DefineParameter(2, ParameterAttributes.None, "value"); - method.DefineParameter(3, ParameterAttributes.None, "options"); - - ILGenerator il = method.GetILGenerator(); - BuildSerialize( - type, - serializationInfo, - il, - () => - { - il.EmitLoadThis(); - il.EmitLdfld(stringByteKeysField); - }, - (index, member) => - { - FieldInfo fi; - if (!customFormatterLookup.TryGetValue(member, out fi)) - { - return null; - } - - return () => - { - il.EmitLoadThis(); - il.EmitLdfld(fi); - }; - }, - 1); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Deserialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual, - type, - new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); - method.DefineParameter(1, ParameterAttributes.None, "reader"); - method.DefineParameter(2, ParameterAttributes.None, "options"); - - ILGenerator il = method.GetILGenerator(); - BuildDeserialize( - type, - serializationInfo, - il, - (index, member) => - { - FieldInfo fi; - if (!customFormatterLookup.TryGetValue(member, out fi)) - { - return null; - } - - return () => - { - il.EmitLoadThis(); - il.EmitLdfld(fi); - }; - }, - 1); // firstArgIndex:0 is this. - } - - return typeBuilder.CreateTypeInfo(); - } - } - - public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKey, bool contractless, bool allowPrivate) - { - var serializationInfo = ObjectSerializationInfo.CreateOrNull(type, forceStringKey, contractless, allowPrivate); - if (serializationInfo == null) - { - return null; - } - - // internal delegate void AnonymousSerializeFunc(byte[][] stringByteKeysField, object[] customFormatters, ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - // internal delegate T AnonymousDeserializeFunc(object[] customFormatters, ref MessagePackReader reader, MessagePackSerializerOptions options); - var serialize = new DynamicMethod("Serialize", null, new[] { typeof(byte[][]), typeof(object[]), typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }, type, true); - DynamicMethod deserialize = null; - - List stringByteKeysField = new List(); - List serializeCustomFormatters = new List(); - List deserializeCustomFormatters = new List(); - - if (serializationInfo.IsStringKey) - { - var i = 0; - foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members.Where(x => x.IsReadable)) - { - stringByteKeysField.Add(Utilities.GetWriterBytes(item.StringKey, (ref MessagePackWriter writer, string arg) => writer.Write(arg))); - i++; - } - } - - foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members.Where(x => x.IsReadable)) - { - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); - if (attr != null) - { - var formatter = Activator.CreateInstance(attr.FormatterType, attr.Arguments); - serializeCustomFormatters.Add(formatter); - } - else - { - serializeCustomFormatters.Add(null); - } - } - - foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members) - { - // not only for writable because for use ctor. - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); - if (attr != null) - { - var formatter = Activator.CreateInstance(attr.FormatterType, attr.Arguments); - deserializeCustomFormatters.Add(formatter); - } - else - { - deserializeCustomFormatters.Add(null); - } - } - - { - ILGenerator il = serialize.GetILGenerator(); - BuildSerialize( - type, - serializationInfo, - il, - () => - { - il.EmitLdarg(0); - }, - (index, member) => - { - if (serializeCustomFormatters.Count == 0) - { - return null; - } - - if (serializeCustomFormatters[index] == null) - { - return null; - } - - return () => - { - il.EmitLdarg(1); // read object[] - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); // object - il.Emit(OpCodes.Castclass, serializeCustomFormatters[index].GetType()); - }; - }, - 2); // 0, 1 is parameter. - } - - if (serializationInfo.IsStruct || serializationInfo.BestmatchConstructor != null) - { - deserialize = new DynamicMethod("Deserialize", type, new[] { typeof(object[]), refMessagePackReader, typeof(MessagePackSerializerOptions) }, type, true); - - ILGenerator il = deserialize.GetILGenerator(); - BuildDeserialize( - type, - serializationInfo, - il, - (index, member) => - { - if (deserializeCustomFormatters.Count == 0) - { - return null; - } - - if (deserializeCustomFormatters[index] == null) - { - return null; - } - - return () => - { - il.EmitLdarg(0); // read object[] - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); // object - il.Emit(OpCodes.Castclass, deserializeCustomFormatters[index].GetType()); - }; - }, - 1); - } - - object serializeDelegate = serialize.CreateDelegate(typeof(AnonymousSerializeFunc<>).MakeGenericType(type)); - object deserializeDelegate = (deserialize == null) - ? (object)null - : (object)deserialize.CreateDelegate(typeof(AnonymousDeserializeFunc<>).MakeGenericType(type)); - var resultFormatter = Activator.CreateInstance( - typeof(AnonymousSerializableFormatter<>).MakeGenericType(type), - new[] { stringByteKeysField.ToArray(), serializeCustomFormatters.ToArray(), deserializeCustomFormatters.ToArray(), serializeDelegate, deserializeDelegate }); - return resultFormatter; - } - - private static void BuildConstructor(Type type, ObjectSerializationInfo info, ConstructorInfo method, FieldBuilder stringByteKeysField, ILGenerator il) - { - il.EmitLoadThis(); - il.Emit(OpCodes.Call, objectCtor); - - var writeCount = info.Members.Count(x => x.IsReadable); - il.EmitLoadThis(); - il.EmitLdc_I4(writeCount); - il.Emit(OpCodes.Newarr, typeof(byte[])); - - var i = 0; - foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable)) - { - il.Emit(OpCodes.Dup); - il.EmitLdc_I4(i); - il.Emit(OpCodes.Ldstr, item.StringKey); - il.EmitCall(CodeGenHelpersTypeInfo.GetEncodedStringBytes); - il.Emit(OpCodes.Stelem_Ref); - i++; - } - - il.Emit(OpCodes.Stfld, stringByteKeysField); - } - - private static Dictionary BuildCustomFormatterField(TypeBuilder builder, ObjectSerializationInfo info, ILGenerator il) - { - Dictionary dict = new Dictionary(); - foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable || x.IsWritable)) - { - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); - if (attr != null) - { - FieldBuilder f = builder.DefineField(item.Name + "_formatter", attr.FormatterType, FieldAttributes.Private | FieldAttributes.InitOnly); - - var bindingFlags = (int)(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - - LocalBuilder attrVar = il.DeclareLocal(typeof(MessagePackFormatterAttribute)); - - il.Emit(OpCodes.Ldtoken, info.Type); - il.EmitCall(EmitInfo.GetTypeFromHandle); - il.Emit(OpCodes.Ldstr, item.Name); - il.EmitLdc_I4(bindingFlags); - if (item.IsProperty) - { - il.EmitCall(EmitInfo.TypeGetProperty); - } - else - { - il.EmitCall(EmitInfo.TypeGetField); - } - - il.EmitTrue(); - il.EmitCall(EmitInfo.GetCustomAttributeMessagePackFormatterAttribute); - il.EmitStloc(attrVar); - - il.EmitLoadThis(); - - il.EmitLdloc(attrVar); - il.EmitCall(EmitInfo.MessagePackFormatterAttr.FormatterType); - il.EmitLdloc(attrVar); - il.EmitCall(EmitInfo.MessagePackFormatterAttr.Arguments); - il.EmitCall(EmitInfo.ActivatorCreateInstance); - - il.Emit(OpCodes.Castclass, attr.FormatterType); - il.Emit(OpCodes.Stfld, f); - - dict.Add(item, f); - } - } - - return dict; - } - - // void Serialize(ref [arg:1]MessagePackWriter writer, [arg:2]T value, [arg:3]MessagePackSerializerOptions options); - private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGenerator il, Action emitStringByteKeys, Func tryEmitLoadCustomFormatter, int firstArgIndex) - { - var argWriter = new ArgumentField(il, firstArgIndex); - var argValue = new ArgumentField(il, firstArgIndex + 1, type); - var argOptions = new ArgumentField(il, firstArgIndex + 2); - - // if(value == null) return WriteNil - if (type.GetTypeInfo().IsClass) - { - Label elseBody = il.DefineLabel(); - - argValue.EmitLoad(); - il.Emit(OpCodes.Brtrue_S, elseBody); - argWriter.EmitLoad(); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - il.Emit(OpCodes.Ret); - - il.MarkLabel(elseBody); - } - - // IMessagePackSerializationCallbackReceiver.OnBeforeSerialize() - if (type.GetTypeInfo().ImplementedInterfaces.Any(x => x == typeof(IMessagePackSerializationCallbackReceiver))) - { - // call directly - MethodInfo[] runtimeMethods = type.GetRuntimeMethods().Where(x => x.Name == "OnBeforeSerialize").ToArray(); - if (runtimeMethods.Length == 1) - { - argValue.EmitLoad(); - il.Emit(OpCodes.Call, runtimeMethods[0]); // don't use EmitCall helper(must use 'Call') - } - else - { - argValue.EmitLdarg(); // force ldarg - il.EmitBoxOrDoNothing(type); - il.EmitCall(onBeforeSerialize); - } - } - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - argOptions.EmitLoad(); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - if (info.IsIntKey) - { - // use Array - var maxKey = info.Members.Where(x => x.IsReadable).Select(x => x.IntKey).DefaultIfEmpty(-1).Max(); - var intKeyMap = info.Members.Where(x => x.IsReadable).ToDictionary(x => x.IntKey); - - var len = maxKey + 1; - argWriter.EmitLoad(); - il.EmitLdc_I4(len); - il.EmitCall(MessagePackWriterTypeInfo.WriteArrayHeader); - - var index = 0; - for (int i = 0; i <= maxKey; i++) - { - ObjectSerializationInfo.EmittableMember member; - if (intKeyMap.TryGetValue(i, out member)) - { - EmitSerializeValue(il, type.GetTypeInfo(), member, index++, tryEmitLoadCustomFormatter, argWriter, argValue, argOptions, localResolver); - } - else - { - // Write Nil as Blanc - argWriter.EmitLoad(); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - } - } - } - else - { - // use Map - var writeCount = info.Members.Count(x => x.IsReadable); - - argWriter.EmitLoad(); - il.EmitLdc_I4(writeCount); - ////if (writeCount <= MessagePackRange.MaxFixMapCount) - ////{ - //// il.EmitCall(MessagePackWriterTypeInfo.WriteFixedMapHeaderUnsafe); - ////} - ////else - { - il.EmitCall(MessagePackWriterTypeInfo.WriteMapHeader); - } - - var index = 0; - foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable)) - { - argWriter.EmitLoad(); - emitStringByteKeys(); - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); - il.Emit(OpCodes.Call, ReadOnlySpanFromByteArray); // convert byte[] to ReadOnlySpan - - // Optimize, WriteRaw(Unity, large) or UnsafeMemory32/64.WriteRawX -#if !UNITY_2018_3_OR_NEWER - var valueLen = CodeGenHelpers.GetEncodedStringBytes(item.StringKey).Length; - if (valueLen <= MessagePackRange.MaxFixStringLength) - { - if (UnsafeMemory.Is32Bit) - { - il.EmitCall(typeof(UnsafeMemory32).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })); - } - else - { - il.EmitCall(typeof(UnsafeMemory64).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })); - } - } - else -#endif - { - il.EmitCall(MessagePackWriterTypeInfo.WriteRaw); - } - - EmitSerializeValue(il, type.GetTypeInfo(), item, index, tryEmitLoadCustomFormatter, argWriter, argValue, argOptions, localResolver); - index++; - } - } - - il.Emit(OpCodes.Ret); - } - - private static void EmitSerializeValue(ILGenerator il, TypeInfo type, ObjectSerializationInfo.EmittableMember member, int index, Func tryEmitLoadCustomFormatter, ArgumentField argWriter, ArgumentField argValue, ArgumentField argOptions, LocalBuilder localResolver) - { - Label endLabel = il.DefineLabel(); - Type t = member.Type; - Action emitter = tryEmitLoadCustomFormatter(index, member); - if (emitter != null) - { - emitter(); - argWriter.EmitLoad(); - argValue.EmitLoad(); - member.EmitLoadValue(il); - argOptions.EmitLoad(); - il.EmitCall(getSerialize(t)); - } - else if (IsOptimizeTargetType(t)) - { - if (!t.GetTypeInfo().IsValueType) - { - // As a nullable type (e.g. byte[] and string) we need to call WriteNil for null values. - Label writeNonNilValueLabel = il.DefineLabel(); - LocalBuilder memberValue = il.DeclareLocal(t); - argValue.EmitLoad(); - member.EmitLoadValue(il); - il.Emit(OpCodes.Dup); - il.EmitStloc(memberValue); - il.Emit(OpCodes.Brtrue, writeNonNilValueLabel); - argWriter.EmitLoad(); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - il.Emit(OpCodes.Br, endLabel); - - il.MarkLabel(writeNonNilValueLabel); - argWriter.EmitLoad(); - il.EmitLdloc(memberValue); - } - else - { - argWriter.EmitLoad(); - argValue.EmitLoad(); - member.EmitLoadValue(il); - } - - if (t == typeof(byte[])) - { - il.EmitCall(ReadOnlySpanFromByteArray); - il.EmitCall(MessagePackWriterTypeInfo.WriteBytes); - } - else - { - il.EmitCall(typeof(MessagePackWriter).GetRuntimeMethod("Write", new Type[] { t })); - } - } - else - { - il.EmitLdloc(localResolver); - il.Emit(OpCodes.Call, getFormatterWithVerify.MakeGenericMethod(t)); - - argWriter.EmitLoad(); - argValue.EmitLoad(); - member.EmitLoadValue(il); - argOptions.EmitLoad(); - il.EmitCall(getSerialize(t)); - } - - il.MarkLabel(endLabel); - } - - // T Deserialize([arg:1]ref MessagePackReader reader, [arg:2]MessagePackSerializerOptions options); - private static void BuildDeserialize(Type type, ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, int firstArgIndex) - { - var reader = new ArgumentField(il, firstArgIndex, @ref: true); - var argOptions = new ArgumentField(il, firstArgIndex + 1); - - // if(reader.TryReadNil()) { return null; } - Label falseLabel = il.DefineLabel(); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.TryReadNil); - il.Emit(OpCodes.Brfalse_S, falseLabel); - if (type.GetTypeInfo().IsClass) - { - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Ret); - } - else - { - il.Emit(OpCodes.Ldstr, "typecode is null, struct not supported"); - il.Emit(OpCodes.Newobj, messagePackSerializationExceptionMessageOnlyConstructor); - il.Emit(OpCodes.Throw); - } - - il.MarkLabel(falseLabel); - - // options.Security.DepthStep(ref reader); - argOptions.EmitLoad(); - il.EmitCall(getSecurityFromOptions); - reader.EmitLdarg(); - il.EmitCall(securityDepthStep); - - // var length = ReadMapHeader(ref byteSequence); - LocalBuilder length = il.DeclareLocal(typeof(int)); // [loc:1] - reader.EmitLdarg(); - - if (info.IsIntKey) - { - il.EmitCall(MessagePackReaderTypeInfo.ReadArrayHeader); - } - else - { - il.EmitCall(MessagePackReaderTypeInfo.ReadMapHeader); - } - - il.EmitStloc(length); - - // make local fields - Label? gotoDefault = null; - DeserializeInfo[] infoList; - if (info.IsIntKey) - { - var maxKey = info.Members.Select(x => x.IntKey).DefaultIfEmpty(-1).Max(); - var len = maxKey + 1; - var intKeyMap = info.Members.ToDictionary(x => x.IntKey); - - infoList = Enumerable.Range(0, len) - .Select(x => - { - ObjectSerializationInfo.EmittableMember member; - if (intKeyMap.TryGetValue(x, out member)) - { - return new DeserializeInfo - { - MemberInfo = member, - LocalField = il.DeclareLocal(member.Type), - SwitchLabel = il.DefineLabel(), - }; - } - else - { - // return null MemberInfo, should filter null - if (gotoDefault == null) - { - gotoDefault = il.DefineLabel(); - } - - return new DeserializeInfo - { - MemberInfo = null, - LocalField = null, - SwitchLabel = gotoDefault.Value, - }; - } - }) - .ToArray(); - } - else - { - infoList = info.Members - .Select(item => new DeserializeInfo - { - MemberInfo = item, - LocalField = il.DeclareLocal(item.Type), - //// SwitchLabel = il.DefineLabel() - }) - .ToArray(); - } - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - argOptions.EmitLoad(); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - // Read Loop(for var i = 0; i < length; i++) - if (info.IsStringKey) - { - var automata = new AutomataDictionary(); - for (int i = 0; i < info.Members.Length; i++) - { - automata.Add(info.Members[i].StringKey, i); - } - - LocalBuilder buffer = il.DeclareLocal(typeof(ReadOnlySpan)); - LocalBuilder longKey = il.DeclareLocal(typeof(ulong)); - - // for (int i = 0; i < len; i++) - il.EmitIncrementFor(length, forILocal => - { - Label readNext = il.DefineLabel(); - Label loopEnd = il.DefineLabel(); - - reader.EmitLdarg(); - il.EmitCall(ReadStringSpan); - il.EmitStloc(buffer); - - // gen automata name lookup - automata.EmitMatch( - il, - buffer, - longKey, - x => - { - var i = x.Value; - if (infoList[i].MemberInfo != null) - { - EmitDeserializeValue(il, infoList[i], i, tryEmitLoadCustomFormatter, reader, argOptions, localResolver); - il.Emit(OpCodes.Br, loopEnd); - } - else - { - il.Emit(OpCodes.Br, readNext); - } - }, - () => - { - il.Emit(OpCodes.Br, readNext); - }); - - il.MarkLabel(readNext); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.Skip); - - il.MarkLabel(loopEnd); - }); - } - else - { - LocalBuilder key = il.DeclareLocal(typeof(int)); - Label switchDefault = il.DefineLabel(); - - il.EmitIncrementFor(length, forILocal => - { - Label loopEnd = il.DefineLabel(); - - il.EmitLdloc(forILocal); - il.EmitStloc(key); - - // switch... local = Deserialize - il.EmitLdloc(key); - - il.Emit(OpCodes.Switch, infoList.Select(x => x.SwitchLabel).ToArray()); - - il.MarkLabel(switchDefault); - - // default, only read. reader.ReadNextBlock(); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.Skip); - il.Emit(OpCodes.Br, loopEnd); - - if (gotoDefault != null) - { - il.MarkLabel(gotoDefault.Value); - il.Emit(OpCodes.Br, switchDefault); - } - - var i = 0; - foreach (DeserializeInfo item in infoList) - { - if (item.MemberInfo != null) - { - il.MarkLabel(item.SwitchLabel); - EmitDeserializeValue(il, item, i++, tryEmitLoadCustomFormatter, reader, argOptions, localResolver); - il.Emit(OpCodes.Br, loopEnd); - } - } - - il.MarkLabel(loopEnd); - }); - } - - // create result object - LocalBuilder structLocal = EmitNewObject(il, type, info, infoList); - - // IMessagePackSerializationCallbackReceiver.OnAfterDeserialize() - if (type.GetTypeInfo().ImplementedInterfaces.Any(x => x == typeof(IMessagePackSerializationCallbackReceiver))) - { - // call directly - MethodInfo[] runtimeMethods = type.GetRuntimeMethods().Where(x => x.Name == "OnAfterDeserialize").ToArray(); - if (runtimeMethods.Length == 1) - { - if (info.IsClass) - { - il.Emit(OpCodes.Dup); - } - else - { - il.EmitLdloca(structLocal); - } - - il.Emit(OpCodes.Call, runtimeMethods[0]); // don't use EmitCall helper(must use 'Call') - } - else - { - if (info.IsStruct) - { - il.EmitLdloc(structLocal); - il.Emit(OpCodes.Box, type); - } - else - { - il.Emit(OpCodes.Dup); - } - - il.EmitCall(onAfterDeserialize); - } - } - - // reader.Depth--; - reader.EmitLdarg(); - il.Emit(OpCodes.Dup); - il.EmitCall(readerDepthGet); - il.Emit(OpCodes.Ldc_I4_1); - il.Emit(OpCodes.Sub_Ovf); - il.EmitCall(readerDepthSet); - - if (info.IsStruct) - { - il.Emit(OpCodes.Ldloc, structLocal); - } - - il.Emit(OpCodes.Ret); - } - - private static void EmitDeserializeValue(ILGenerator il, DeserializeInfo info, int index, Func tryEmitLoadCustomFormatter, ArgumentField argReader, ArgumentField argOptions, LocalBuilder localResolver) - { - Label storeLabel = il.DefineLabel(); - ObjectSerializationInfo.EmittableMember member = info.MemberInfo; - Type t = member.Type; - Action emitter = tryEmitLoadCustomFormatter(index, member); - if (emitter != null) - { - emitter(); - argReader.EmitLdarg(); - argOptions.EmitLoad(); - il.EmitCall(getDeserialize(t)); - } - else if (IsOptimizeTargetType(t)) - { - if (!t.GetTypeInfo().IsValueType) - { - // As a nullable type (e.g. byte[] and string) we need to first call TryReadNil - // if (reader.TryReadNil()) - Label readNonNilValueLabel = il.DefineLabel(); - argReader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.TryReadNil); - il.Emit(OpCodes.Brfalse_S, readNonNilValueLabel); - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Br, storeLabel); - - il.MarkLabel(readNonNilValueLabel); - } - - argReader.EmitLdarg(); - if (t == typeof(byte[])) - { - LocalBuilder local = il.DeclareLocal(typeof(ReadOnlySequence?)); - il.EmitCall(MessagePackReaderTypeInfo.ReadBytes); - il.EmitStloc(local); - il.EmitLdloca(local); - il.EmitCall(ArrayFromNullableReadOnlySequence); - } - else - { - il.EmitCall(MessagePackReaderTypeInfo.TypeInfo.GetDeclaredMethods("Read" + t.Name).First(x => x.GetParameters().Length == 0)); - } - } - else - { - il.EmitLdloc(localResolver); - il.EmitCall(getFormatterWithVerify.MakeGenericMethod(t)); - argReader.EmitLdarg(); - argOptions.EmitLoad(); - il.EmitCall(getDeserialize(t)); - } - - il.MarkLabel(storeLabel); - il.EmitStloc(info.LocalField); - } - - private static LocalBuilder EmitNewObject(ILGenerator il, Type type, ObjectSerializationInfo info, DeserializeInfo[] members) - { - if (info.IsClass) - { - EmitNewObjectConstructorArguments(il, info, members); - - il.Emit(OpCodes.Newobj, info.BestmatchConstructor); - - foreach (DeserializeInfo item in members.Where(x => x.MemberInfo != null && x.MemberInfo.IsWritable)) - { - il.Emit(OpCodes.Dup); - il.EmitLdloc(item.LocalField); - item.MemberInfo.EmitStoreValue(il); - } - - return null; - } - else - { - LocalBuilder result = il.DeclareLocal(type); - if (info.BestmatchConstructor == null) - { - il.Emit(OpCodes.Ldloca, result); - il.Emit(OpCodes.Initobj, type); - } - else - { - EmitNewObjectConstructorArguments(il, info, members); - - il.Emit(OpCodes.Newobj, info.BestmatchConstructor); - il.Emit(OpCodes.Stloc, result); - } - - foreach (DeserializeInfo item in members.Where(x => x.MemberInfo != null && x.MemberInfo.IsWritable)) - { - il.EmitLdloca(result); - il.EmitLdloc(item.LocalField); - item.MemberInfo.EmitStoreValue(il); - } - - return result; // struct returns local result field - } - } - - private static void EmitNewObjectConstructorArguments(ILGenerator il, ObjectSerializationInfo info, DeserializeInfo[] members) - { - foreach (ObjectSerializationInfo.EmittableMemberAndConstructorParameter item in info.ConstructorParameters) - { - DeserializeInfo local = members.First(x => x.MemberInfo == item.MemberInfo); - il.EmitLdloc(local.LocalField); - - if (!item.ConstructorParameter.ParameterType.IsValueType && local.MemberInfo.IsValueType) - { - // When a constructor argument of type object is being provided by a serialized member value that is a value type - // then that value must be boxed in order for the generated code to be valid (see issue #987). This may occur because - // the only requirement when determining whether a member value may be used to populate a constructor argument in an - // IsAssignableFrom check and typeof(object) IsAssignableFrom typeof(int), for example. - il.Emit(OpCodes.Box, local.MemberInfo.Type); - } - } - } - - /// - /// Keep this list in sync with ShouldUseFormatterResolverHelper.PrimitiveTypes. - /// - private static bool IsOptimizeTargetType(Type type) - { - return type == typeof(Int16) - || type == typeof(Int32) - || type == typeof(Int64) - || type == typeof(UInt16) - || type == typeof(UInt32) - || type == typeof(UInt64) - || type == typeof(Single) - || type == typeof(Double) - || type == typeof(bool) - || type == typeof(byte) - || type == typeof(sbyte) - || type == typeof(char) - || type == typeof(byte[]) - - // Do not include types that resolvers are allowed to modify. - ////|| type == typeof(DateTime) // OldSpec has no support, so for that and perf reasons a .NET native DateTime resolver exists. - ////|| type == typeof(string) // https://github.com/Cysharp/MasterMemory provides custom formatter for string interning. - ; - } - -#pragma warning disable SA1311 // Static readonly fields should begin with upper-case letter - - // EmitInfos... - private static readonly Type refMessagePackReader = typeof(MessagePackReader).MakeByRefType(); - - private static readonly MethodInfo ReadOnlySpanFromByteArray = typeof(ReadOnlySpan).GetRuntimeMethod("op_Implicit", new[] { typeof(byte[]) }); - private static readonly MethodInfo ReadStringSpan = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.ReadStringSpan), new[] { typeof(MessagePackReader).MakeByRefType() }); - private static readonly MethodInfo ArrayFromNullableReadOnlySequence = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetArrayFromNullableSequence), new[] { typeof(ReadOnlySequence?).MakeByRefType() }); - - private static readonly MethodInfo getFormatterWithVerify = typeof(FormatterResolverExtensions).GetRuntimeMethods().First(x => x.Name == nameof(FormatterResolverExtensions.GetFormatterWithVerify)); - private static readonly MethodInfo getResolverFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Resolver)).GetMethod; - private static readonly MethodInfo getSecurityFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Security)).GetMethod; - private static readonly MethodInfo securityDepthStep = typeof(MessagePackSecurity).GetRuntimeMethod(nameof(MessagePackSecurity.DepthStep), new[] { typeof(MessagePackReader).MakeByRefType() }); - private static readonly MethodInfo readerDepthGet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth)).GetMethod; - private static readonly MethodInfo readerDepthSet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth)).SetMethod; - private static readonly Func getSerialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Serialize), new[] { typeof(MessagePackWriter).MakeByRefType(), t, typeof(MessagePackSerializerOptions) }); - private static readonly Func getDeserialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Deserialize), new[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); - //// static readonly ConstructorInfo dictionaryConstructor = typeof(ByteArrayStringHashTable).GetTypeInfo().DeclaredConstructors.First(x => { var p = x.GetParameters(); return p.Length == 1 && p[0].ParameterType == typeof(int); }); - //// static readonly MethodInfo dictionaryAdd = typeof(ByteArrayStringHashTable).GetRuntimeMethod("Add", new[] { typeof(string), typeof(int) }); - //// static readonly MethodInfo dictionaryTryGetValue = typeof(ByteArrayStringHashTable).GetRuntimeMethod("TryGetValue", new[] { typeof(ArraySegment), refInt }); - private static readonly ConstructorInfo messagePackSerializationExceptionMessageOnlyConstructor = typeof(MessagePackSerializationException).GetTypeInfo().DeclaredConstructors.First(x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 1 && p[0].ParameterType == typeof(string); - }); - - private static readonly MethodInfo onBeforeSerialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnBeforeSerialize), Type.EmptyTypes); - private static readonly MethodInfo onAfterDeserialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnAfterDeserialize), Type.EmptyTypes); - - private static readonly ConstructorInfo objectCtor = typeof(object).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0); - -#pragma warning restore SA1311 // Static readonly fields should begin with upper-case letter - - /// - /// Helps match parameters when searching a method when the parameter is a generic type. - /// - private static bool Matches(MethodInfo m, int parameterIndex, Type desiredType) - { - ParameterInfo[] parameters = m.GetParameters(); - return parameters.Length > parameterIndex - ////&& parameters[0].ParameterType.IsGenericType // returns false for some bizarre reason - && parameters[parameterIndex].ParameterType.Name == desiredType.Name - && parameters[parameterIndex].ParameterType.Namespace == desiredType.Namespace; - } - - internal static class MessagePackWriterTypeInfo - { - internal static readonly TypeInfo TypeInfo = typeof(MessagePackWriter).GetTypeInfo(); - - internal static readonly MethodInfo WriteMapHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteMapHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteArrayHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteArrayHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteBytes = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { typeof(ReadOnlySpan) }); - internal static readonly MethodInfo WriteNil = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteNil), Type.EmptyTypes); - internal static readonly MethodInfo WriteRaw = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteRaw), new[] { typeof(ReadOnlySpan) }); - } - - internal static class MessagePackReaderTypeInfo - { - internal static readonly TypeInfo TypeInfo = typeof(MessagePackReader).GetTypeInfo(); - - internal static readonly MethodInfo ReadArrayHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadArrayHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadMapHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadMapHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadBytes = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadBytes), Type.EmptyTypes); - internal static readonly MethodInfo TryReadNil = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.TryReadNil), Type.EmptyTypes); - internal static readonly MethodInfo Skip = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.Skip), Type.EmptyTypes); - } - - internal static class CodeGenHelpersTypeInfo - { - public static readonly MethodInfo GetEncodedStringBytes = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetEncodedStringBytes), new[] { typeof(string) }); - } - - internal static class EmitInfo - { - public static readonly MethodInfo GetTypeFromHandle = ExpressionUtility.GetMethodInfo(() => Type.GetTypeFromHandle(default(RuntimeTypeHandle))); - public static readonly MethodInfo TypeGetProperty = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetProperty(default(string), default(BindingFlags))); - public static readonly MethodInfo TypeGetField = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetField(default(string), default(BindingFlags))); - public static readonly MethodInfo GetCustomAttributeMessagePackFormatterAttribute = ExpressionUtility.GetMethodInfo(() => CustomAttributeExtensions.GetCustomAttribute(default(MemberInfo), default(bool))); - public static readonly MethodInfo ActivatorCreateInstance = ExpressionUtility.GetMethodInfo(() => Activator.CreateInstance(default(Type), default(object[]))); - - internal static class MessagePackFormatterAttr - { - internal static readonly MethodInfo FormatterType = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.FormatterType).GetGetMethod(); - internal static readonly MethodInfo Arguments = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.Arguments).GetGetMethod(); - } - } - - private class DeserializeInfo - { - public ObjectSerializationInfo.EmittableMember MemberInfo { get; set; } - - public LocalBuilder LocalField { get; set; } - - public Label SwitchLabel { get; set; } - } - } - - internal delegate void AnonymousSerializeFunc(byte[][] stringByteKeysField, object[] customFormatters, ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); - - internal delegate T AnonymousDeserializeFunc(object[] customFormatters, ref MessagePackReader reader, MessagePackSerializerOptions options); - - internal class AnonymousSerializableFormatter : IMessagePackFormatter - { - private readonly byte[][] stringByteKeysField; - private readonly object[] serializeCustomFormatters; - private readonly object[] deserializeCustomFormatters; - private readonly AnonymousSerializeFunc serialize; - private readonly AnonymousDeserializeFunc deserialize; - - public AnonymousSerializableFormatter(byte[][] stringByteKeysField, object[] serializeCustomFormatters, object[] deserializeCustomFormatters, AnonymousSerializeFunc serialize, AnonymousDeserializeFunc deserialize) - { - this.stringByteKeysField = stringByteKeysField; - this.serializeCustomFormatters = serializeCustomFormatters; - this.deserializeCustomFormatters = deserializeCustomFormatters; - this.serialize = serialize; - this.deserialize = deserialize; - } - - public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) - { - if (this.serialize == null) - { - throw new MessagePackSerializationException(this.GetType().Name + " does not support Serialize."); - } - - this.serialize(this.stringByteKeysField, this.serializeCustomFormatters, ref writer, value, options); - } - - public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (this.deserialize == null) - { - throw new MessagePackSerializationException(this.GetType().Name + " does not support Deserialize."); - } - - return this.deserialize(this.deserializeCustomFormatters, ref reader, options); - } - } - - internal class ObjectSerializationInfo - { - public Type Type { get; set; } - - public bool IsIntKey { get; set; } - - public bool IsStringKey - { - get { return !this.IsIntKey; } - } - - public bool IsClass { get; set; } - - public bool IsStruct - { - get { return !this.IsClass; } - } - - public ConstructorInfo BestmatchConstructor { get; set; } - - public EmittableMemberAndConstructorParameter[] ConstructorParameters { get; set; } - - public EmittableMember[] Members { get; set; } - - private ObjectSerializationInfo() - { - } - - public static ObjectSerializationInfo CreateOrNull(Type type, bool forceStringKey, bool contractless, bool allowPrivate) - { - TypeInfo ti = type.GetTypeInfo(); - var isClass = ti.IsClass || ti.IsInterface || ti.IsAbstract; - var isStruct = ti.IsValueType; - - MessagePackObjectAttribute contractAttr = ti.GetCustomAttributes().FirstOrDefault(); - DataContractAttribute dataContractAttr = ti.GetCustomAttribute(); - if (contractAttr == null && dataContractAttr == null && !forceStringKey && !contractless) - { - return null; - } - - var isIntKey = true; - var intMembers = new Dictionary(); - var stringMembers = new Dictionary(); - - if (forceStringKey || contractless || (contractAttr != null && contractAttr.KeyAsPropertyName)) - { - // All public members are serialize target except [Ignore] member. - isIntKey = !(forceStringKey || (contractAttr != null && contractAttr.KeyAsPropertyName)); - - var hiddenIntKey = 0; - - // Group the properties and fields by name to qualify members of the same name - // (declared with the 'new' keyword) with the declaring type. - IEnumerable> membersByName = type.GetRuntimeProperties() - .Concat(type.GetRuntimeFields().Cast()) - .OrderBy(m => m.DeclaringType, OrderBaseTypesBeforeDerivedTypes.Instance) - .GroupBy(m => m.Name); - foreach (var memberGroup in membersByName) - { - bool firstMemberByName = true; - foreach (MemberInfo item in memberGroup) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - EmittableMember member; - if (item is PropertyInfo property) - { - if (property.IsIndexer()) - { - continue; - } - - MethodInfo getMethod = property.GetGetMethod(true); - MethodInfo setMethod = property.GetSetMethod(true); - - member = new EmittableMember - { - PropertyInfo = property, - IsReadable = (getMethod != null) && (allowPrivate || getMethod.IsPublic) && !getMethod.IsStatic, - IsWritable = (setMethod != null) && (allowPrivate || setMethod.IsPublic) && !setMethod.IsStatic, - StringKey = firstMemberByName ? item.Name : $"{item.DeclaringType.FullName}.{item.Name}", - }; - } - else if (item is FieldInfo field) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (field.IsStatic) - { - continue; - } - - member = new EmittableMember - { - FieldInfo = field, - IsReadable = allowPrivate || field.IsPublic, - IsWritable = allowPrivate || (field.IsPublic && !field.IsInitOnly), - StringKey = firstMemberByName ? item.Name : $"{item.DeclaringType.FullName}.{item.Name}", - }; - } - else - { - throw new MessagePackSerializationException("unexpected member type"); - } - - if (!member.IsReadable && !member.IsWritable) - { - continue; - } - - member.IntKey = hiddenIntKey++; - if (isIntKey) - { - intMembers.Add(member.IntKey, member); - } - else - { - stringMembers.Add(member.StringKey, member); - } - - firstMemberByName = false; - } - } - } - else - { - // Public members with KeyAttribute except [Ignore] member. - var searchFirst = true; - var hiddenIntKey = 0; - - foreach (PropertyInfo item in GetAllProperties(type)) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.IsIndexer()) - { - continue; - } - - MethodInfo getMethod = item.GetGetMethod(true); - MethodInfo setMethod = item.GetSetMethod(true); - - var member = new EmittableMember - { - PropertyInfo = item, - IsReadable = (getMethod != null) && (allowPrivate || getMethod.IsPublic) && !getMethod.IsStatic, - IsWritable = (setMethod != null) && (allowPrivate || setMethod.IsPublic) && !setMethod.IsStatic, - }; - if (!member.IsReadable && !member.IsWritable) - { - continue; - } - - KeyAttribute key; - if (contractAttr != null) - { - // MessagePackObjectAttribute - key = item.GetCustomAttribute(true); - if (key == null) - { - throw new MessagePackDynamicObjectResolverException("all public members must mark KeyAttribute or IgnoreMemberAttribute." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IsExplicitContract = true; - if (key.IntKey == null && key.StringKey == null) - { - throw new MessagePackDynamicObjectResolverException("both IntKey and StringKey are null." + " type: " + type.FullName + " member:" + item.Name); - } - } - else - { - // DataContractAttribute - DataMemberAttribute pseudokey = item.GetCustomAttribute(true); - if (pseudokey == null) - { - // This member has no DataMemberAttribute nor IgnoreMemberAttribute. - // But the type *did* have a DataContractAttribute on it, so no attribute implies the member should not be serialized. - continue; - } - - member.IsExplicitContract = true; - - // use Order first - if (pseudokey.Order != -1) - { - key = new KeyAttribute(pseudokey.Order); - } - else if (pseudokey.Name != null) - { - key = new KeyAttribute(pseudokey.Name); - } - else - { - key = new KeyAttribute(item.Name); // use property name - } - } - - if (searchFirst) - { - searchFirst = false; - isIntKey = key.IntKey != null; - } - else - { - if ((isIntKey && key.IntKey == null) || (!isIntKey && key.StringKey == null)) - { - throw new MessagePackDynamicObjectResolverException("all members key type must be same." + " type: " + type.FullName + " member:" + item.Name); - } - } - - if (isIntKey) - { - member.IntKey = key.IntKey.Value; - if (intMembers.TryGetValue(member.IntKey, out EmittableMember conflictingMember)) - { - // Quietly skip duplicate if this is an override property. - if ((conflictingMember.PropertyInfo.SetMethod?.IsVirtual ?? false) || (conflictingMember.PropertyInfo.GetMethod?.IsVirtual ?? false)) - { - continue; - } - - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - intMembers.Add(member.IntKey, member); - } - else - { - member.StringKey = key.StringKey; - if (stringMembers.TryGetValue(member.StringKey, out EmittableMember conflictingMember)) - { - // Quietly skip duplicate if this is an override property. - if ((conflictingMember.PropertyInfo.SetMethod?.IsVirtual ?? false) || (conflictingMember.PropertyInfo.GetMethod?.IsVirtual ?? false)) - { - continue; - } - - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IntKey = hiddenIntKey++; - stringMembers.Add(member.StringKey, member); - } - } - - foreach (FieldInfo item in GetAllFields(type)) - { - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.GetCustomAttribute(true) != null) - { - continue; - } - - if (item.IsStatic) - { - continue; - } - - var member = new EmittableMember - { - FieldInfo = item, - IsReadable = allowPrivate || item.IsPublic, - IsWritable = allowPrivate || (item.IsPublic && !item.IsInitOnly), - }; - if (!member.IsReadable && !member.IsWritable) - { - continue; - } - - KeyAttribute key; - if (contractAttr != null) - { - // MessagePackObjectAttribute - key = item.GetCustomAttribute(true); - if (key == null) - { - throw new MessagePackDynamicObjectResolverException("all public members must mark KeyAttribute or IgnoreMemberAttribute." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IsExplicitContract = true; - if (key.IntKey == null && key.StringKey == null) - { - throw new MessagePackDynamicObjectResolverException("both IntKey and StringKey are null." + " type: " + type.FullName + " member:" + item.Name); - } - } - else - { - // DataContractAttribute - DataMemberAttribute pseudokey = item.GetCustomAttribute(true); - if (pseudokey == null) - { - // This member has no DataMemberAttribute nor IgnoreMemberAttribute. - // But the type *did* have a DataContractAttribute on it, so no attribute implies the member should not be serialized. - continue; - } - - member.IsExplicitContract = true; - - // use Order first - if (pseudokey.Order != -1) - { - key = new KeyAttribute(pseudokey.Order); - } - else if (pseudokey.Name != null) - { - key = new KeyAttribute(pseudokey.Name); - } - else - { - key = new KeyAttribute(item.Name); // use property name - } - } - - if (searchFirst) - { - searchFirst = false; - isIntKey = key.IntKey != null; - } - else - { - if ((isIntKey && key.IntKey == null) || (!isIntKey && key.StringKey == null)) - { - throw new MessagePackDynamicObjectResolverException("all members key type must be same." + " type: " + type.FullName + " member:" + item.Name); - } - } - - if (isIntKey) - { - member.IntKey = key.IntKey.Value; - if (intMembers.ContainsKey(member.IntKey)) - { - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - intMembers.Add(member.IntKey, member); - } - else - { - member.StringKey = key.StringKey; - if (stringMembers.ContainsKey(member.StringKey)) - { - throw new MessagePackDynamicObjectResolverException("key is duplicated, all members key must be unique." + " type: " + type.FullName + " member:" + item.Name); - } - - member.IntKey = hiddenIntKey++; - stringMembers.Add(member.StringKey, member); - } - } - } - - // GetConstructor - IEnumerator ctorEnumerator = null; - ConstructorInfo ctor = ti.DeclaredConstructors.SingleOrDefault(x => x.GetCustomAttribute(false) != null); - if (ctor == null) - { - ctorEnumerator = - ti.DeclaredConstructors.Where(x => !x.IsStatic && (allowPrivate || x.IsPublic)).OrderByDescending(x => x.GetParameters().Length) - .GetEnumerator(); - - if (ctorEnumerator.MoveNext()) - { - ctor = ctorEnumerator.Current; - } - } - - // struct allows null ctor - if (ctor == null && !isStruct) - { - throw new MessagePackDynamicObjectResolverException("can't find public constructor. type:" + type.FullName); - } - - var constructorParameters = new List(); - if (ctor != null) - { - ILookup> constructorLookupByKeyDictionary = stringMembers.ToLookup(x => x.Key, x => x, StringComparer.OrdinalIgnoreCase); - ILookup> constructorLookupByMemberNameDictionary = stringMembers.ToLookup(x => x.Value.Name, x => x, StringComparer.OrdinalIgnoreCase); - do - { - constructorParameters.Clear(); - var ctorParamIndex = 0; - foreach (ParameterInfo item in ctor.GetParameters()) - { - EmittableMember paramMember; - if (isIntKey) - { - if (intMembers.TryGetValue(ctorParamIndex, out paramMember)) - { - if ((item.ParameterType == paramMember.Type || - item.ParameterType.GetTypeInfo().IsAssignableFrom(paramMember.Type)) - && paramMember.IsReadable) - { - constructorParameters.Add(new EmittableMemberAndConstructorParameter { ConstructorParameter = item, MemberInfo = paramMember }); - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, parameterType mismatch. type:" + type.FullName + " parameterIndex:" + ctorParamIndex + " paramterType:" + item.ParameterType.Name); - } - } - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, index not found. type:" + type.FullName + " parameterIndex:" + ctorParamIndex); - } - } - } - else - { - // Lookup by both string key name and member name - IEnumerable> hasKey = constructorLookupByKeyDictionary[item.Name]; - IEnumerable> hasKeyByMemberName = constructorLookupByMemberNameDictionary[item.Name]; - - var lenByKey = hasKey.Count(); - var lenByMemberName = hasKeyByMemberName.Count(); - - var len = lenByKey; - - // Prefer to use string key name unless a matching string key is not found but a matching member name is - if (lenByKey == 0 && lenByMemberName != 0) - { - len = lenByMemberName; - hasKey = hasKeyByMemberName; - } - - if (len != 0) - { - if (len != 1) - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("duplicate matched constructor parameter name:" + type.FullName + " parameterName:" + item.Name + " paramterType:" + item.ParameterType.Name); - } - } - - paramMember = hasKey.First().Value; - if (item.ParameterType.IsAssignableFrom(paramMember.Type) && paramMember.IsReadable) - { - constructorParameters.Add(new EmittableMemberAndConstructorParameter { ConstructorParameter = item, MemberInfo = paramMember }); - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, parameterType mismatch. type:" + type.FullName + " parameterName:" + item.Name + " paramterType:" + item.ParameterType.Name); - } - } - } - else - { - if (ctorEnumerator != null) - { - ctor = null; - continue; - } - else - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor parameter, index not found. type:" + type.FullName + " parameterName:" + item.Name); - } - } - } - - ctorParamIndex++; - } - } - while (TryGetNextConstructor(ctorEnumerator, ref ctor)); - - if (ctor == null) - { - throw new MessagePackDynamicObjectResolverException("can't find matched constructor. type:" + type.FullName); - } - } - - EmittableMember[] members; - if (isIntKey) - { - members = intMembers.Values.OrderBy(x => x.IntKey).ToArray(); - } - else - { - members = stringMembers.Values - .OrderBy(x => - { - DataMemberAttribute attr = x.GetDataMemberAttribute(); - if (attr == null) - { - return int.MaxValue; - } - - return attr.Order; - }) - .ToArray(); - } - - return new ObjectSerializationInfo - { - Type = type, - IsClass = isClass, - BestmatchConstructor = ctor, - ConstructorParameters = constructorParameters.ToArray(), - IsIntKey = isIntKey, - Members = members.Where(m => m.IsExplicitContract || constructorParameters.Any(p => p.MemberInfo.Equals(m)) || m.IsWritable).ToArray(), - }; - } - - private static IEnumerable GetAllFields(Type type) - { - if (type.BaseType is object) - { - foreach (var item in GetAllFields(type.BaseType)) - { - yield return item; - } - } - - // with declared only - foreach (var item in type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) - { - yield return item; - } - } - - private static IEnumerable GetAllProperties(Type type) - { - if (type.BaseType is object) - { - foreach (var item in GetAllProperties(type.BaseType)) - { - yield return item; - } - } - - // with declared only - foreach (var item in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) - { - yield return item; - } - } - - private static bool TryGetNextConstructor(IEnumerator ctorEnumerator, ref ConstructorInfo ctor) - { - if (ctorEnumerator == null || ctor != null) - { - return false; - } - - if (ctorEnumerator.MoveNext()) - { - ctor = ctorEnumerator.Current; - return true; - } - else - { - ctor = null; - return false; - } - } - - public class EmittableMemberAndConstructorParameter - { - public EmittableMember MemberInfo { get; set; } - - public ParameterInfo ConstructorParameter { get; set; } - } - - public class EmittableMember - { - public bool IsProperty - { - get { return this.PropertyInfo != null; } - } - - public bool IsField - { - get { return this.FieldInfo != null; } - } - - public bool IsWritable { get; set; } - - public bool IsReadable { get; set; } - - public int IntKey { get; set; } - - public string StringKey { get; set; } - - public Type Type - { - get { return this.IsField ? this.FieldInfo.FieldType : this.PropertyInfo.PropertyType; } - } - - public FieldInfo FieldInfo { get; set; } - - public PropertyInfo PropertyInfo { get; set; } - - public string Name - { - get - { - return this.IsProperty ? this.PropertyInfo.Name : this.FieldInfo.Name; - } - } - - public bool IsValueType - { - get - { - Type t = this.IsProperty ? this.PropertyInfo.PropertyType : this.FieldInfo.FieldType; - return t.IsValueType; - } - } - - /// - /// Gets or sets a value indicating whether this member is explicitly opted in with an attribute. - /// - public bool IsExplicitContract { get; set; } - - public MessagePackFormatterAttribute GetMessagePackFormatterAttribute() - { - if (this.IsProperty) - { - return (MessagePackFormatterAttribute)this.PropertyInfo.GetCustomAttribute(true); - } - else - { - return (MessagePackFormatterAttribute)this.FieldInfo.GetCustomAttribute(true); - } - } - - public DataMemberAttribute GetDataMemberAttribute() - { - if (this.IsProperty) - { - return (DataMemberAttribute)this.PropertyInfo.GetCustomAttribute(true); - } - else - { - return (DataMemberAttribute)this.FieldInfo.GetCustomAttribute(true); - } - } - - public void EmitLoadValue(ILGenerator il) - { - if (this.IsProperty) - { - il.EmitCall(this.PropertyInfo.GetGetMethod(true)); - } - else - { - il.Emit(OpCodes.Ldfld, this.FieldInfo); - } - } - - public void EmitStoreValue(ILGenerator il) - { - if (this.IsProperty) - { - il.EmitCall(this.PropertyInfo.GetSetMethod(true)); - } - else - { - il.Emit(OpCodes.Stfld, this.FieldInfo); - } - } - - ////public object ReflectionLoadValue(object value) - ////{ - //// if (IsProperty) - //// { - //// return PropertyInfo.GetValue(value, null); - //// } - //// else - //// { - //// return FieldInfo.GetValue(value); - //// } - ////} - - ////public void ReflectionStoreValue(object obj, object value) - ////{ - //// if (IsProperty) - //// { - //// PropertyInfo.SetValue(obj, value, null); - //// } - //// else - //// { - //// FieldInfo.SetValue(obj, value); - //// } - ////} - } - - private class OrderBaseTypesBeforeDerivedTypes : IComparer - { - internal static readonly OrderBaseTypesBeforeDerivedTypes Instance = new OrderBaseTypesBeforeDerivedTypes(); - - private OrderBaseTypesBeforeDerivedTypes() - { - } - - public int Compare(Type x, Type y) - { - return - x.IsEquivalentTo(y) ? 0 : - x.IsAssignableFrom(y) ? -1 : - y.IsAssignableFrom(x) ? 1 : - 0; - } - } - } - - internal class MessagePackDynamicObjectResolverException : MessagePackSerializationException - { - public MessagePackDynamicObjectResolverException(string message) - : base(message) - { - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs.meta deleted file mode 100644 index 397a144..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c701699b2f5475d448a963b344407181 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicUnionResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicUnionResolver.cs deleted file mode 100644 index fa9ad5b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicUnionResolver.cs +++ /dev/null @@ -1,496 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Text.RegularExpressions; -using System.Threading; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1509 // Opening braces should not be preceded by blank line - -namespace MessagePack.Resolvers -{ - /// - /// UnionResolver by dynamic code generation. - /// - public sealed class DynamicUnionResolver : IFormatterResolver - { - private const string ModuleName = "MessagePack.Resolvers.DynamicUnionResolver"; - - /// - /// The singleton instance that can be used. - /// - public static readonly DynamicUnionResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly Lazy DynamicAssembly; -#if !UNITY_2018_3_OR_NEWER - private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+", RegexOptions.Compiled); -#else - private static readonly Regex SubtractFullNameRegex = new Regex(@", Version=\d+.\d+.\d+.\d+, Culture=\w+, PublicKeyToken=\w+"); -#endif - - private static int nameSequence = 0; - - static DynamicUnionResolver() - { - Instance = new DynamicUnionResolver(); - Options = new MessagePackSerializerOptions(Instance); - DynamicAssembly = new Lazy(() => new DynamicAssembly(ModuleName)); - } - - private DynamicUnionResolver() - { - } - -#if NETFRAMEWORK - public AssemblyBuilder Save() - { - return DynamicAssembly.Value.Save(); - } -#endif - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - TypeInfo ti = typeof(T).GetTypeInfo(); - if (ti.IsNullable()) - { - ti = ti.GenericTypeArguments[0].GetTypeInfo(); - - var innerFormatter = DynamicUnionResolver.Instance.GetFormatterDynamic(ti.AsType()); - if (innerFormatter == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); - return; - } - - TypeInfo formatterTypeInfo = BuildType(typeof(T)); - if (formatterTypeInfo == null) - { - return; - } - - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); - } - } - - private static TypeInfo BuildType(Type type) - { - TypeInfo ti = type.GetTypeInfo(); - - // order by key(important for use jump-table of switch) - UnionAttribute[] unionAttrs = ti.GetCustomAttributes().OrderBy(x => x.Key).ToArray(); - - if (unionAttrs.Length == 0) - { - return null; - } - - if (!ti.IsInterface && !ti.IsAbstract) - { - throw new MessagePackDynamicUnionResolverException("Union can only be interface or abstract class. Type:" + type.Name); - } - - var checker1 = new HashSet(); - var checker2 = new HashSet(); - foreach (UnionAttribute item in unionAttrs) - { - if (!checker1.Add(item.Key)) - { - throw new MessagePackDynamicUnionResolverException("Same union key has found. Type:" + type.Name + " Key:" + item.Key); - } - - if (!checker2.Add(item.SubType)) - { - throw new MessagePackDynamicUnionResolverException("Same union subType has found. Type:" + type.Name + " SubType: " + item.SubType); - } - } - - Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - using (MonoProtection.EnterRefEmitLock()) - { - TypeBuilder typeBuilder = DynamicAssembly.Value.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - - FieldBuilder typeToKeyAndJumpMap = null; // Dictionary> - FieldBuilder keyToJumpMap = null; // Dictionary - - // create map dictionary - { - ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); - typeToKeyAndJumpMap = typeBuilder.DefineField("typeToKeyAndJumpMap", typeof(Dictionary>), FieldAttributes.Private | FieldAttributes.InitOnly); - keyToJumpMap = typeBuilder.DefineField("keyToJumpMap", typeof(Dictionary), FieldAttributes.Private | FieldAttributes.InitOnly); - - ILGenerator il = method.GetILGenerator(); - BuildConstructor(type, unionAttrs, method, typeToKeyAndJumpMap, keyToJumpMap, il); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Serialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, - null, - new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - BuildSerialize(type, unionAttrs, method, typeToKeyAndJumpMap, il); - } - - { - MethodBuilder method = typeBuilder.DefineMethod( - "Deserialize", - MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, - type, - new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); - - ILGenerator il = method.GetILGenerator(); - BuildDeserialize(type, unionAttrs, method, keyToJumpMap, il); - } - - return typeBuilder.CreateTypeInfo(); - } - } - - private static void BuildConstructor(Type type, UnionAttribute[] infos, ConstructorInfo method, FieldBuilder typeToKeyAndJumpMap, FieldBuilder keyToJumpMap, ILGenerator il) - { - il.EmitLdarg(0); - il.Emit(OpCodes.Call, objectCtor); - - { - il.EmitLdarg(0); - il.EmitLdc_I4(infos.Length); - il.Emit(OpCodes.Ldsfld, runtimeTypeHandleEqualityComparer); - il.Emit(OpCodes.Newobj, typeMapDictionaryConstructor); - - var index = 0; - foreach (UnionAttribute item in infos) - { - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Ldtoken, item.SubType); - il.EmitLdc_I4(item.Key); - il.EmitLdc_I4(index); - il.Emit(OpCodes.Newobj, intIntKeyValuePairConstructor); - il.EmitCall(typeMapDictionaryAdd); - - index++; - } - - il.Emit(OpCodes.Stfld, typeToKeyAndJumpMap); - } - - { - il.EmitLdarg(0); - il.EmitLdc_I4(infos.Length); - il.Emit(OpCodes.Newobj, keyMapDictionaryConstructor); - - var index = 0; - foreach (UnionAttribute item in infos) - { - il.Emit(OpCodes.Dup); - il.EmitLdc_I4(item.Key); - il.EmitLdc_I4(index); - il.EmitCall(keyMapDictionaryAdd); - - index++; - } - - il.Emit(OpCodes.Stfld, keyToJumpMap); - } - - il.Emit(OpCodes.Ret); - } - - // void Serialize([arg:1]MessagePackWriter writer, [arg:2]T value, [arg:3]MessagePackSerializerOptions options); - private static void BuildSerialize(Type type, UnionAttribute[] infos, MethodBuilder method, FieldBuilder typeToKeyAndJumpMap, ILGenerator il) - { - // if(value == null) return WriteNil - Label elseBody = il.DefineLabel(); - Label notFoundType = il.DefineLabel(); - - il.EmitLdarg(2); - il.Emit(OpCodes.Brtrue_S, elseBody); - il.Emit(OpCodes.Br, notFoundType); - il.MarkLabel(elseBody); - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - il.EmitLdarg(3); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - LocalBuilder keyPair = il.DeclareLocal(typeof(KeyValuePair)); - - il.EmitLoadThis(); - il.EmitLdfld(typeToKeyAndJumpMap); - il.EmitLdarg(2); - il.EmitCall(objectGetType); - il.EmitCall(getTypeHandle); - il.EmitLdloca(keyPair); - il.EmitCall(typeMapDictionaryTryGetValue); - il.Emit(OpCodes.Brfalse, notFoundType); - - // writer.WriteArrayHeader(2, false); - il.EmitLdarg(1); - il.EmitLdc_I4(2); - il.EmitCall(MessagePackWriterTypeInfo.WriteArrayHeader); - - // writer.Write(keyPair.Key) - il.EmitLdarg(1); - il.EmitLdloca(keyPair); - il.EmitCall(intIntKeyValuePairGetKey); - il.EmitCall(MessagePackWriterTypeInfo.WriteInt32); - - Label loopEnd = il.DefineLabel(); - - // switch-case (offset += resolver.GetFormatter.Serialize(with cast) - var switchLabels = infos.Select(x => new { Label = il.DefineLabel(), Attr = x }).ToArray(); - il.EmitLdloca(keyPair); - il.EmitCall(intIntKeyValuePairGetValue); - il.Emit(OpCodes.Switch, switchLabels.Select(x => x.Label).ToArray()); - il.Emit(OpCodes.Br, loopEnd); // default - - foreach (var item in switchLabels) - { - il.MarkLabel(item.Label); - il.EmitLdloc(localResolver); - il.Emit(OpCodes.Call, getFormatterWithVerify.MakeGenericMethod(item.Attr.SubType)); - - il.EmitLdarg(1); - il.EmitLdarg(2); - if (item.Attr.SubType.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Unbox_Any, item.Attr.SubType); - } - else - { - il.Emit(OpCodes.Castclass, item.Attr.SubType); - } - - il.EmitLdarg(3); - il.Emit(OpCodes.Callvirt, getSerialize(item.Attr.SubType)); - - il.Emit(OpCodes.Br, loopEnd); - } - - // return; - il.MarkLabel(loopEnd); - il.Emit(OpCodes.Ret); - - // else, return WriteNil - il.MarkLabel(notFoundType); - il.EmitLdarg(1); - il.EmitCall(MessagePackWriterTypeInfo.WriteNil); - il.Emit(OpCodes.Ret); - } - - // T Deserialize([arg:1]ref MessagePackReader reader, [arg:2]MessagePackSerializerOptions options); - private static void BuildDeserialize(Type type, UnionAttribute[] infos, MethodBuilder method, FieldBuilder keyToJumpMap, ILGenerator il) - { - // if(MessagePackBinary.TryReadNil()) { return null; } - Label falseLabel = il.DefineLabel(); - il.EmitLdarg(1); - il.EmitCall(MessagePackReaderTypeInfo.TryReadNil); - il.Emit(OpCodes.Brfalse_S, falseLabel); - - il.Emit(OpCodes.Ldnull); - il.Emit(OpCodes.Ret); - - il.MarkLabel(falseLabel); - - // IFormatterResolver resolver = options.Resolver; - LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver)); - il.EmitLdarg(2); - il.EmitCall(getResolverFromOptions); - il.EmitStloc(localResolver); - - // read-array header and validate, reader.ReadArrayHeader() != 2) throw; - Label rightLabel = il.DefineLabel(); - var reader = new ArgumentField(il, 1); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.ReadArrayHeader); - il.EmitLdc_I4(2); - il.Emit(OpCodes.Beq_S, rightLabel); - il.Emit(OpCodes.Ldstr, "Invalid Union data was detected. Type:" + type.FullName); - il.Emit(OpCodes.Newobj, invalidOperationExceptionConstructor); - il.Emit(OpCodes.Throw); - - il.MarkLabel(rightLabel); - - // read key - LocalBuilder key = il.DeclareLocal(typeof(int)); - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.ReadInt32); - il.EmitStloc(key); - - // is-sequential don't need else convert key to jump-table value - if (!IsZeroStartSequential(infos)) - { - Label endKeyMapGet = il.DefineLabel(); - il.EmitLdarg(0); - il.EmitLdfld(keyToJumpMap); - il.EmitLdloc(key); - il.EmitLdloca(key); - il.EmitCall(keyMapDictionaryTryGetValue); - il.Emit(OpCodes.Brtrue_S, endKeyMapGet); - il.EmitLdc_I4(-1); - il.EmitStloc(key); - - il.MarkLabel(endKeyMapGet); - } - - // switch->read - LocalBuilder result = il.DeclareLocal(type); - Label loopEnd = il.DefineLabel(); - il.Emit(OpCodes.Ldnull); - il.EmitStloc(result); - il.Emit(OpCodes.Ldloc, key); - - var switchLabels = infos.Select(x => new { Label = il.DefineLabel(), Attr = x }).ToArray(); - il.Emit(OpCodes.Switch, switchLabels.Select(x => x.Label).ToArray()); - - // default - reader.EmitLdarg(); - il.EmitCall(MessagePackReaderTypeInfo.Skip); - il.Emit(OpCodes.Br, loopEnd); - - foreach (var item in switchLabels) - { - il.MarkLabel(item.Label); - il.EmitLdloc(localResolver); - il.EmitCall(getFormatterWithVerify.MakeGenericMethod(item.Attr.SubType)); - il.EmitLdarg(1); - il.EmitLdarg(2); - il.EmitCall(getDeserialize(item.Attr.SubType)); - if (item.Attr.SubType.GetTypeInfo().IsValueType) - { - il.Emit(OpCodes.Box, item.Attr.SubType); - } - - il.Emit(OpCodes.Stloc, result); - il.Emit(OpCodes.Br, loopEnd); - } - - il.MarkLabel(loopEnd); - - il.Emit(OpCodes.Ldloc, result); - il.Emit(OpCodes.Ret); - } - - private static bool IsZeroStartSequential(UnionAttribute[] infos) - { - for (int i = 0; i < infos.Length; i++) - { - if (infos[i].Key != i) - { - return false; - } - } - - return true; - } - -#pragma warning disable SA1311 // Static readonly fields should begin with upper-case letter - - // EmitInfos... - private static readonly Type refMessagePackReader = typeof(MessagePackReader).MakeByRefType(); - private static readonly Type refKvp = typeof(KeyValuePair).MakeByRefType(); - private static readonly MethodInfo getFormatterWithVerify = typeof(FormatterResolverExtensions).GetRuntimeMethods().First(x => x.Name == "GetFormatterWithVerify"); - private static readonly MethodInfo getResolverFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Resolver)).GetMethod; - - private static readonly Func getSerialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), t, typeof(MessagePackSerializerOptions) }); - private static readonly Func getDeserialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod("Deserialize", new[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) }); - - private static readonly FieldInfo runtimeTypeHandleEqualityComparer = typeof(RuntimeTypeHandleEqualityComparer).GetRuntimeField("Default"); - private static readonly ConstructorInfo intIntKeyValuePairConstructor = typeof(KeyValuePair).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 2); - private static readonly ConstructorInfo typeMapDictionaryConstructor = typeof(Dictionary>).GetTypeInfo().DeclaredConstructors.First(x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 2 && p[0].ParameterType == typeof(int); - }); - - private static readonly MethodInfo typeMapDictionaryAdd = typeof(Dictionary>).GetRuntimeMethod("Add", new[] { typeof(RuntimeTypeHandle), typeof(KeyValuePair) }); - private static readonly MethodInfo typeMapDictionaryTryGetValue = typeof(Dictionary>).GetRuntimeMethod("TryGetValue", new[] { typeof(RuntimeTypeHandle), refKvp }); - - private static readonly ConstructorInfo keyMapDictionaryConstructor = typeof(Dictionary).GetTypeInfo().DeclaredConstructors.First(x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 1 && p[0].ParameterType == typeof(int); - }); - - private static readonly MethodInfo keyMapDictionaryAdd = typeof(Dictionary).GetRuntimeMethod("Add", new[] { typeof(int), typeof(int) }); - private static readonly MethodInfo keyMapDictionaryTryGetValue = typeof(Dictionary).GetRuntimeMethod("TryGetValue", new[] { typeof(int), typeof(int).MakeByRefType() }); - - private static readonly MethodInfo objectGetType = typeof(object).GetRuntimeMethod("GetType", Type.EmptyTypes); - private static readonly MethodInfo getTypeHandle = typeof(Type).GetRuntimeProperty("TypeHandle").GetGetMethod(); - - private static readonly MethodInfo intIntKeyValuePairGetKey = typeof(KeyValuePair).GetRuntimeProperty("Key").GetGetMethod(); - private static readonly MethodInfo intIntKeyValuePairGetValue = typeof(KeyValuePair).GetRuntimeProperty("Value").GetGetMethod(); - - private static readonly ConstructorInfo invalidOperationExceptionConstructor = typeof(System.InvalidOperationException).GetTypeInfo().DeclaredConstructors.First( - x => - { - ParameterInfo[] p = x.GetParameters(); - return p.Length == 1 && p[0].ParameterType == typeof(string); - }); - - private static readonly ConstructorInfo objectCtor = typeof(object).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0); - -#pragma warning restore SA1311 // Static readonly fields should begin with upper-case letter - - private static class MessagePackReaderTypeInfo - { - internal static readonly TypeInfo ReaderTypeInfo = typeof(MessagePackReader).GetTypeInfo(); - - internal static readonly MethodInfo ReadBytes = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadBytes), Type.EmptyTypes); - internal static readonly MethodInfo ReadInt32 = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadInt32), Type.EmptyTypes); - internal static readonly MethodInfo ReadString = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadString), Type.EmptyTypes); - internal static readonly MethodInfo TryReadNil = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.TryReadNil), Type.EmptyTypes); - internal static readonly MethodInfo Skip = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.Skip), Type.EmptyTypes); - internal static readonly MethodInfo ReadArrayHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadArrayHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadMapHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadMapHeader), Type.EmptyTypes); - } - - private static class MessagePackWriterTypeInfo - { - internal static readonly TypeInfo WriterTypeInfo = typeof(MessagePackWriter).GetTypeInfo(); - - internal static readonly MethodInfo WriteArrayHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteArrayHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteInt32 = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { typeof(int) }); - internal static readonly MethodInfo WriteNil = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteNil), Type.EmptyTypes); - } - } - - internal class MessagePackDynamicUnionResolverException : MessagePackSerializationException - { - public MessagePackDynamicUnionResolverException(string message) - : base(message) - { - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicUnionResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicUnionResolver.cs.meta deleted file mode 100644 index 9dc1aa9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/DynamicUnionResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bf9a25b7376eeda47ab1f62b045063bb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ExpandoObjectResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ExpandoObjectResolver.cs deleted file mode 100644 index e050fa7..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ExpandoObjectResolver.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Collections.Generic; -using System.Dynamic; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - /// - /// A resolver for use when deserializing MessagePack data where the schema is not known at compile-time - /// such that strong-types can be instantiated. - /// Instead, is used wherever a MessagePack map is encountered. - /// - public static class ExpandoObjectResolver - { - /// - /// The resolver to use to deserialize into C#'s dynamic keyword. - /// - /// - /// This resolver includes more than just the . - /// - public static readonly IFormatterResolver Instance = CompositeResolver.Create( - new IMessagePackFormatter[] - { - ExpandoObjectFormatter.Instance, - new PrimitiveObjectWithExpandoMaps(), - }, - new IFormatterResolver[] { BuiltinResolver.Instance }); - - /// - /// A set of options that includes the - /// and puts the deserializer into mode. - /// - public static readonly MessagePackSerializerOptions Options = MessagePackSerializerOptions.Standard - .WithSecurity(MessagePackSecurity.UntrustedData) // when the schema isn't known beforehand, that generally suggests you don't know/trust the data. - .WithResolver(Instance); - - private class PrimitiveObjectWithExpandoMaps : PrimitiveObjectFormatter - { - protected override object DeserializeMap(ref MessagePackReader reader, int length, MessagePackSerializerOptions options) - { - IMessagePackFormatter keyFormatter = options.Resolver.GetFormatterWithVerify(); - IMessagePackFormatter objectFormatter = options.Resolver.GetFormatter(); - IDictionary dictionary = new ExpandoObject(); - for (int i = 0; i < length; i++) - { - var key = keyFormatter.Deserialize(ref reader, options); - var value = objectFormatter.Deserialize(ref reader, options); - dictionary.Add(key, value); - } - - return dictionary; - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ExpandoObjectResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ExpandoObjectResolver.cs.meta deleted file mode 100644 index c88fc43..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/ExpandoObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 96998b3cb6d6e044c95e399ea6d6da96 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDateTimeResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDateTimeResolver.cs deleted file mode 100644 index 4e23631..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDateTimeResolver.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using MessagePack.Formatters; -using MessagePack.Internal; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - public sealed class NativeDateTimeResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly NativeDateTimeResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static NativeDateTimeResolver() - { - Instance = new NativeDateTimeResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private NativeDateTimeResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)NativeDateTimeResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class NativeDateTimeResolverGetFormatterHelper - { - internal static object GetFormatter(Type t) - { - if (t == typeof(DateTime)) - { - return NativeDateTimeFormatter.Instance; - } - else if (t == typeof(DateTime?)) - { - return new StaticNullableFormatter(NativeDateTimeFormatter.Instance); - } - else if (t == typeof(DateTime[])) - { - return NativeDateTimeArrayFormatter.Instance; - } - - return null; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDateTimeResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDateTimeResolver.cs.meta deleted file mode 100644 index 60ab3aa..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDateTimeResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8a20dfff612ed08419192bb868710915 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDecimalResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDecimalResolver.cs deleted file mode 100644 index 725fba1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDecimalResolver.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - public sealed class NativeDecimalResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly NativeDecimalResolver Instance = new NativeDecimalResolver(); - - private NativeDecimalResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static object GetFormatterHelper(Type t) - { - if (t == typeof(Decimal)) - { - return NativeDecimalFormatter.Instance; - } - else if (t == typeof(Decimal?)) - { - return new StaticNullableFormatter(NativeDecimalFormatter.Instance); - } - - return null; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)GetFormatterHelper(typeof(T)); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDecimalResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDecimalResolver.cs.meta deleted file mode 100644 index 8e36b78..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeDecimalResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0711ad34c9883f244a09757b2470ed67 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeGuidResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeGuidResolver.cs deleted file mode 100644 index 34081b1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeGuidResolver.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - public sealed class NativeGuidResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly NativeGuidResolver Instance = new NativeGuidResolver(); - - private NativeGuidResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static object GetFormatterHelper(Type t) - { - if (t == typeof(Guid)) - { - return NativeGuidFormatter.Instance; - } - else if (t == typeof(Guid?)) - { - return new StaticNullableFormatter(NativeGuidFormatter.Instance); - } - - return null; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)GetFormatterHelper(typeof(T)); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeGuidResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeGuidResolver.cs.meta deleted file mode 100644 index 429bb9c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/NativeGuidResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a30757bd25ef7c44ba11a2ecbe64a8c1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/PrimitiveObjectResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/PrimitiveObjectResolver.cs deleted file mode 100644 index 5c28599..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/PrimitiveObjectResolver.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - public sealed class PrimitiveObjectResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly PrimitiveObjectResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static PrimitiveObjectResolver() - { - Instance = new PrimitiveObjectResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private PrimitiveObjectResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (typeof(T) == typeof(object)) - ? (IMessagePackFormatter)(object)PrimitiveObjectFormatter.Instance - : null; - } - } - } - - ////#if !UNITY_2018_3_OR_NEWER - - //// /// - //// /// In `object`, when serializing resolve by concrete type and when deserializing use primitive. - //// /// - //// public sealed class DynamicObjectTypeFallbackResolver : IFormatterResolver - //// { - //// public static readonly DynamicObjectTypeFallbackResolver Instance = new DynamicObjectTypeFallbackResolver(); - - //// DynamicObjectTypeFallbackResolver() - //// { - - //// } - - //// public IMessagePackFormatter GetFormatter() - //// { - //// return FormatterCache.formatter; - //// } - - //// static class FormatterCache - //// { - //// public static readonly IMessagePackFormatter formatter; - - //// static FormatterCache() - //// { - //// formatter = (typeof(T) == typeof(object)) - //// ? (IMessagePackFormatter)(object)DynamicObjectTypeFallbackFormatter.Instance - //// : null; - //// } - //// } - //// } - - ////#endif -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/PrimitiveObjectResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/PrimitiveObjectResolver.cs.meta deleted file mode 100644 index d87b469..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/PrimitiveObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9e84d60bb85b40b458a001118316145d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StandardResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StandardResolver.cs deleted file mode 100644 index 009e050..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StandardResolver.cs +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Linq; -using MessagePack.Formatters; -using MessagePack.Internal; -using MessagePack.Resolvers; - -#pragma warning disable SA1403 // File may only contain a single namespace - -namespace MessagePack.Resolvers -{ - /// - /// Default composited resolver, builtin -> attribute -> dynamic enum -> dynamic generic -> dynamic union -> dynamic object -> primitive. - /// - public sealed class StandardResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly StandardResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolver.Instance, // Try Object -#endif - }).ToArray(); - - static StandardResolver() - { - Instance = new StandardResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private StandardResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } - - public sealed class ContractlessStandardResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly ContractlessStandardResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolver.Instance, // Try Object - DynamicContractlessObjectResolver.Instance, // Serializes keys as strings -#endif - }).ToArray(); - - static ContractlessStandardResolver() - { - Instance = new ContractlessStandardResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private ContractlessStandardResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } - - public sealed class StandardResolverAllowPrivate : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly StandardResolverAllowPrivate Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolverAllowPrivate.Instance, // Try Object -#endif - }).ToArray(); - - static StandardResolverAllowPrivate() - { - Instance = new StandardResolverAllowPrivate(); - Options = new MessagePackSerializerOptions(Instance); - } - - private StandardResolverAllowPrivate() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } - - public sealed class ContractlessStandardResolverAllowPrivate : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly ContractlessStandardResolverAllowPrivate Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - private static readonly IFormatterResolver[] Resolvers = StandardResolverHelper.DefaultResolvers.Concat(new IFormatterResolver[] - { -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicObjectResolverAllowPrivate.Instance, // Try Object - DynamicContractlessObjectResolverAllowPrivate.Instance, // Serializes keys as strings -#endif - }).ToArray(); - - static ContractlessStandardResolverAllowPrivate() - { - Instance = new ContractlessStandardResolverAllowPrivate(); - Options = new MessagePackSerializerOptions(Instance); - } - - private ContractlessStandardResolverAllowPrivate() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - if (typeof(T) == typeof(object)) - { - // final fallback -#if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; -#else - Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); -#endif - } - else - { - foreach (IFormatterResolver item in Resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } - } -} - -namespace MessagePack.Internal -{ - internal static class StandardResolverHelper - { - public static readonly IFormatterResolver[] DefaultResolvers = new IFormatterResolver[] - { - BuiltinResolver.Instance, // Try Builtin - AttributeFormatterResolver.Instance, // Try use [MessagePackFormatter] - -#if UNITY_2018_3_OR_NEWER - MessagePack.Unity.UnityResolver.Instance, -#else - ImmutableCollection.ImmutableCollectionResolver.Instance, - CompositeResolver.Create(ExpandoObjectFormatter.Instance), -#endif - -#if !ENABLE_IL2CPP - DynamicGenericResolver.Instance, // Try Array, Tuple, Collection, Enum(Generic Fallback) -#endif - -#if !ENABLE_IL2CPP && !NET_STANDARD_2_0 - DynamicUnionResolver.Instance, // Try Union(Interface) -#endif - }; - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StandardResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StandardResolver.cs.meta deleted file mode 100644 index 352e158..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StandardResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 99e7c1a56d89ab645b824dae6b57d67c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StaticCompositeResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StaticCompositeResolver.cs deleted file mode 100644 index ba0084c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StaticCompositeResolver.cs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; - -namespace MessagePack.Resolvers -{ - /// - /// Singleton version of CompositeResolver, which be able to register a collection of formatters and resolvers to a single instance. - /// - public class StaticCompositeResolver : IFormatterResolver - { - public static readonly StaticCompositeResolver Instance = new StaticCompositeResolver(); - - private bool freezed; - private IReadOnlyList formatters; - private IReadOnlyList resolvers; - - private StaticCompositeResolver() - { - formatters = Array.Empty(); - resolvers = Array.Empty(); - } - - /// - /// Initializes a singleton instance with the specified formatters. - /// This method can only call before use StaticCompositeResolver.Instance.GetFormatter. - /// If call twice in the Register methods, registered formatters and resolvers will be overridden. - /// - /// - /// A list of instances of . - /// The formatters are searched in the order given, so if two formatters support serializing the same type, the first one is used. - /// - public void Register(params IMessagePackFormatter[] formatters) - { - if (this.freezed) - { - throw new InvalidOperationException("Register must call on startup(before use GetFormatter)."); - } - - if (this.formatters is null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - this.formatters = formatters; - this.resolvers = Array.Empty(); - } - - /// - /// Initializes a singleton instance with the specified formatters and sub-resolvers. - /// This method can only call before use StaticCompositeResolver.Instance.GetFormatter. - /// If call twice in the Register methods, registered formatters and resolvers will be overridden. - /// - /// - /// A list of resolvers to use for serializing types. - /// The resolvers are searched in the order given, so if two resolvers support serializing the same type, the first one is used. - /// - public void Register(params IFormatterResolver[] resolvers) - { - if (this.freezed) - { - throw new InvalidOperationException("Register must call on startup(before use GetFormatter)."); - } - - if (resolvers is null) - { - throw new ArgumentNullException(nameof(resolvers)); - } - - this.formatters = Array.Empty(); - this.resolvers = resolvers; - } - - /// - /// Initializes a singleton instance with the specified formatters and sub-resolvers. - /// This method can only call before use StaticCompositeResolver.Instance.GetFormatter. - /// If call twice in the Register methods, registered formatters and resolvers will be overridden. - /// - /// - /// A list of instances of . - /// The formatters are searched in the order given, so if two formatters support serializing the same type, the first one is used. - /// - /// - /// A list of resolvers to use for serializing types for which does not include a formatter. - /// The resolvers are searched in the order given, so if two resolvers support serializing the same type, the first one is used. - /// - public void Register(IReadOnlyList formatters, IReadOnlyList resolvers) - { - if (this.freezed) - { - throw new InvalidOperationException("Register must call on startup(before use GetFormatter)."); - } - - if (formatters is null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (resolvers is null) - { - throw new ArgumentNullException(nameof(resolvers)); - } - - this.formatters = formatters; - this.resolvers = resolvers; - } - - /// - /// Gets an instance that can serialize or deserialize some type . - /// - /// The type of value to be serialized or deserialized. - /// A formatter, if this resolver supplies one for type ; otherwise null. - public IMessagePackFormatter GetFormatter() - { - return Cache.Formatter; - } - - private static class Cache - { - public static readonly IMessagePackFormatter Formatter; - - static Cache() - { - Instance.freezed = true; - foreach (var item in Instance.formatters) - { - if (item is IMessagePackFormatter f) - { - Formatter = f; - return; - } - } - - foreach (var item in Instance.resolvers) - { - var f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - return; - } - } - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StaticCompositeResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StaticCompositeResolver.cs.meta deleted file mode 100644 index 3cb0693..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/StaticCompositeResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d904ee272668ccb448b3159036454caf -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs deleted file mode 100644 index df789b9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !UNITY_2018_3_OR_NEWER -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ - /// - /// Embeds the full name of .NET types for typed fields/collection items - /// Preserves .NET timezone. - /// - public sealed class TypelessContractlessStandardResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly TypelessContractlessStandardResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - /// - /// A *private* list of resolvers. If we ever want to expose any of these (so the user can adjust settings, etc.) - /// then we must make this an instance collection instead of a static collection so that each consumer can have their own settings. - /// - private static readonly IReadOnlyList Resolvers = new IFormatterResolver[] - { - NativeDateTimeResolver.Instance, // Native c# DateTime format, preserving timezone - ForceSizePrimitiveObjectResolver.Instance, // Preserve particular integer types - BuiltinResolver.Instance, // Try Builtin - AttributeFormatterResolver.Instance, // Try use [MessagePackFormatter] -#if !ENABLE_IL2CPP - DynamicEnumResolver.Instance, // Try Enum - DynamicGenericResolver.Instance, // Try Array, Tuple, Collection - DynamicUnionResolver.Instance, // Try Union(Interface) - DynamicObjectResolver.Instance, // Try Object -#endif - DynamicContractlessObjectResolverAllowPrivate.Instance, // Serializes keys as strings - TypelessObjectResolver.Instance, - }; - - static TypelessContractlessStandardResolver() - { - Instance = new TypelessContractlessStandardResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private readonly ResolverCache resolverCache = new ResolverCache(Resolvers); - - public IMessagePackFormatter GetFormatter() => this.resolverCache.GetFormatter(); - - private class ResolverCache : CachingFormatterResolver - { - private readonly IReadOnlyList resolvers; - - internal ResolverCache(IReadOnlyList resolvers) - { - this.resolvers = resolvers ?? throw new ArgumentNullException(nameof(resolvers)); - } - - protected override IMessagePackFormatter GetFormatterCore() - { - foreach (IFormatterResolver item in this.resolvers) - { - IMessagePackFormatter f = item.GetFormatter(); - if (f != null) - { - return f; - } - } - - return null; - } - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs.meta deleted file mode 100644 index e5277c1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessContractlessStandardResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6db1c844b382ce54680f6d0ba3476abb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessObjectResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessObjectResolver.cs deleted file mode 100644 index 3633f1c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessObjectResolver.cs +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using MessagePack.Internal; - -namespace MessagePack.Resolvers -{ -#if !UNITY_2018_3_OR_NEWER - - /// - /// Used for `object` fields/collections, ex: var arr = new object[] { 1, "a", new Model() }; - /// The runtime type of value in object field, should be covered by one of resolvers in complex/standard resolver. - /// should be placed before DynamicObjectTypeFallbackResolver and in resolvers list. - /// Deserializer uses Namespace.TypeName, AssemblyName to get runtime type in destination app, so that combination must be present in destination app. - /// Serialized binary is valid MessagePack binary used ext-format and custom typecode(100). - /// Inside ext - assembly qualified type name, and serialized object. - /// - public sealed class TypelessObjectResolver : IFormatterResolver - { - public static readonly IFormatterResolver Instance = new TypelessObjectResolver(); - - private static readonly IFormatterResolver[] Resolvers = new IFormatterResolver[] - { - ForceSizePrimitiveObjectResolver.Instance, - ContractlessStandardResolverAllowPrivate.Instance, - }; - - private TypelessObjectResolver() - { - } - - /// - public IMessagePackFormatter GetFormatter() - { - return Cache.Formatter; - } - - private static class Cache - { - public static readonly IMessagePackFormatter Formatter; - - static Cache() - { - if (typeof(T).IsAbstract || typeof(T).IsInterface) - { - Formatter = new ForceTypelessFormatter(); - } - - if (typeof(T) == typeof(object)) - { - Formatter = (IMessagePackFormatter)TypelessFormatter.Instance; - } - else - { - foreach (var item in Resolvers) - { - var f = item.GetFormatter(); - if (f != null) - { - Formatter = f; - } - } - } - } - } - } - - /* helpers for TypelessFormatter */ - - internal sealed class ForceSizePrimitiveObjectResolver : IFormatterResolver - { - /// - /// The singleton instance that can be used. - /// - public static readonly ForceSizePrimitiveObjectResolver Instance; - - /// - /// A instance with this formatter pre-configured. - /// - public static readonly MessagePackSerializerOptions Options; - - static ForceSizePrimitiveObjectResolver() - { - Instance = new ForceSizePrimitiveObjectResolver(); - Options = new MessagePackSerializerOptions(Instance); - } - - private ForceSizePrimitiveObjectResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)Helper.GetFormatter(typeof(T)); - } - } - - private static class Helper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - // Primitive - { typeof(Int16), ForceInt16BlockFormatter.Instance }, - { typeof(Int32), ForceInt32BlockFormatter.Instance }, - { typeof(Int64), ForceInt64BlockFormatter.Instance }, - { typeof(UInt16), ForceUInt16BlockFormatter.Instance }, - { typeof(UInt32), ForceUInt32BlockFormatter.Instance }, - { typeof(UInt64), ForceUInt64BlockFormatter.Instance }, - { typeof(byte), ForceByteBlockFormatter.Instance }, - { typeof(sbyte), ForceSByteBlockFormatter.Instance }, - - // Nullable Primitive - { typeof(Int16?), NullableForceInt16BlockFormatter.Instance }, - { typeof(Int32?), NullableForceInt32BlockFormatter.Instance }, - { typeof(Int64?), NullableForceInt64BlockFormatter.Instance }, - { typeof(UInt16?), NullableForceUInt16BlockFormatter.Instance }, - { typeof(UInt32?), NullableForceUInt32BlockFormatter.Instance }, - { typeof(UInt64?), NullableForceUInt64BlockFormatter.Instance }, - { typeof(byte?), NullableForceByteBlockFormatter.Instance }, - { typeof(sbyte?), NullableForceSByteBlockFormatter.Instance }, - - // optimized primitive array formatter - { typeof(Int16[]), ForceInt16BlockArrayFormatter.Instance }, - { typeof(Int32[]), ForceInt32BlockArrayFormatter.Instance }, - { typeof(Int64[]), ForceInt64BlockArrayFormatter.Instance }, - { typeof(UInt16[]), ForceUInt16BlockArrayFormatter.Instance }, - { typeof(UInt32[]), ForceUInt32BlockArrayFormatter.Instance }, - { typeof(UInt64[]), ForceUInt64BlockArrayFormatter.Instance }, - { typeof(SByte[]), ForceSByteBlockArrayFormatter.Instance }, - }; - - public static object GetFormatter(Type type) - { - object formatter; - return FormatterMap.TryGetValue(type, out formatter) - ? formatter - : null; - } - } - } - -#endif -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessObjectResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessObjectResolver.cs.meta deleted file mode 100644 index f80b0ee..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Resolvers/TypelessObjectResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 38df7384160fb4d478fcae83f15f45b2 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SafeBitConverter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SafeBitConverter.cs deleted file mode 100644 index 7eb77a0..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SafeBitConverter.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Runtime.InteropServices; - -namespace MessagePack -{ - internal static class SafeBitConverter - { - internal static long ToInt64(ReadOnlySpan value) - { -#if UNITY_ANDROID - if (BitConverter.IsLittleEndian) - { - int i1 = value[0] | (value[1] << 8) | (value[2] << 16) | (value[3] << 24); - int i2 = value[4] | (value[5] << 8) | (value[6] << 16) | (value[7] << 24); - return (uint)i1 | ((long)i2 << 32); - } - else - { - int i1 = (value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]; - int i2 = (value[4] << 24) | (value[5] << 16) | (value[6] << 8) | value[7]; - return (uint)i2 | ((long)i1 << 32); - } -#else - return MemoryMarshal.Cast(value)[0]; -#endif - } - - internal static ulong ToUInt64(ReadOnlySpan value) => unchecked((ulong)ToInt64(value)); - - internal static ushort ToUInt16(ReadOnlySpan value) - { -#if UNITY_ANDROID - if (BitConverter.IsLittleEndian) - { - return (ushort)(value[0] | (value[1] << 8)); - } - else - { - return (ushort)((value[0] << 8) | value[1]); - } -#else - return MemoryMarshal.Cast(value)[0]; -#endif - } - - internal static uint ToUInt32(ReadOnlySpan value) - { -#if UNITY_ANDROID - if (BitConverter.IsLittleEndian) - { - return (uint)(value[0] | (value[1] << 8) | (value[2] << 16) | (value[3] << 24)); - } - else - { - return (uint)((value[0] << 24) | (value[1] << 16) | (value[2] << 8) | value[3]); - } -#else - return MemoryMarshal.Cast(value)[0]; -#endif - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SafeBitConverter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SafeBitConverter.cs.meta deleted file mode 100644 index d498a08..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SafeBitConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1a2f0bfda50859f4abf45bc978ea8b16 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequencePool.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequencePool.cs deleted file mode 100644 index bdfc073..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequencePool.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using Nerdbank.Streams; - -namespace MessagePack -{ - /// - /// A thread-safe, alloc-free reusable object pool. - /// - internal class SequencePool - { - /// - /// A thread-safe pool of reusable objects. - /// - /// - /// We use a that allows every processor to be involved in messagepack serialization concurrently, - /// plus one nested serialization per processor (since LZ4 and sometimes other nested serializations may exist). - /// - internal static readonly SequencePool Shared = new SequencePool(Environment.ProcessorCount * 2); - - /// - /// The value to use for . - /// - /// - /// Individual users that want a different value for this can modify the setting on the rented - /// or by supplying their own . - /// - /// - /// We use 32KB so that when LZ4Codec.MaximumOutputLength is used on this length it does not require a - /// buffer that would require the Large Object Heap. - /// - private const int MinimumSpanLength = 32 * 1024; - - private readonly int maxSize; - private readonly Stack> pool = new Stack>(); - - /// - /// The array pool which we share with all objects created by this instance. - /// - /// - /// We allow 100 arrays to be shared (instead of the default 50) and reduce the max array length from the default 1MB to something more reasonable for our expected use. - /// - private readonly ArrayPool arrayPool = ArrayPool.Create(80 * 1024, 100); - - /// - /// Initializes a new instance of the class. - /// - /// The maximum size to allow the pool to grow. - internal SequencePool(int maxSize) - { - this.maxSize = maxSize; - } - - /// - /// Gets an instance of - /// This is taken from the recycled pool if one is available; otherwise a new one is created. - /// - /// The rental tracker that provides access to the object as well as a means to return it. - internal Rental Rent() - { - lock (this.pool) - { - if (this.pool.Count > 0) - { - return new Rental(this, this.pool.Pop()); - } - } - - // Configure the newly created object to share a common array pool with the other instances, - // otherwise each one will have its own ArrayPool which would likely waste a lot of memory. - return new Rental(this, new Sequence(this.arrayPool) { MinimumSpanLength = MinimumSpanLength }); - } - - private void Return(Sequence value) - { - value.Reset(); - lock (this.pool) - { - if (this.pool.Count < this.maxSize) - { - // Reset to preferred settings in case the renter changed them. - value.MinimumSpanLength = MinimumSpanLength; - - this.pool.Push(value); - } - } - } - - internal struct Rental : IDisposable - { - private readonly SequencePool owner; - - internal Rental(SequencePool owner, Sequence value) - { - this.owner = owner; - this.Value = value; - } - - /// - /// Gets the recyclable object. - /// - public Sequence Value { get; } - - /// - /// Returns the recyclable object to the pool. - /// - /// - /// The instance is cleaned first, if a clean delegate was provided. - /// It is dropped instead of being returned to the pool if the pool is already at its maximum size. - /// - public void Dispose() - { - this.owner?.Return(this.Value); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequencePool.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequencePool.cs.meta deleted file mode 100644 index 81aeb27..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequencePool.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 97164d8f34ce72f459fc5dff3dc7370f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReader.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReader.cs deleted file mode 100644 index 475ccc2..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReader.cs +++ /dev/null @@ -1,497 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* Licensed to the .NET Foundation under one or more agreements. - * The .NET Foundation licenses this file to you under the MIT license. - * See the LICENSE file in the project root for more information. */ - -using System; -using System.Buffers; -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace MessagePack -{ - internal ref partial struct SequenceReader - where T : unmanaged, IEquatable - { - /// - /// A value indicating whether we're using (as opposed to . - /// - private bool usingSequence; - - /// - /// Backing for the entire sequence when we're not using . - /// - private ReadOnlySequence sequence; - - /// - /// The position at the start of the . - /// - private SequencePosition currentPosition; - - /// - /// The position at the end of the . - /// - private SequencePosition nextPosition; - - /// - /// Backing for the entire sequence when we're not using . - /// - private ReadOnlyMemory memory; - - /// - /// A value indicating whether there is unread data remaining. - /// - private bool moreData; - - /// - /// The total number of elements in the sequence. - /// - private long length; - - /// - /// Initializes a new instance of the struct - /// over the given . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public SequenceReader(in ReadOnlySequence sequence) - { - this.usingSequence = true; - this.CurrentSpanIndex = 0; - this.Consumed = 0; - this.sequence = sequence; - this.memory = default; - this.currentPosition = sequence.Start; - this.length = -1; - - ReadOnlySpan first = sequence.First.Span; - this.nextPosition = sequence.GetPosition(first.Length); - this.CurrentSpan = first; - this.moreData = first.Length > 0; - - if (!this.moreData && !sequence.IsSingleSegment) - { - this.moreData = true; - this.GetNextSpan(); - } - } - - /// - /// Initializes a new instance of the struct - /// over the given . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public SequenceReader(ReadOnlyMemory memory) - { - this.usingSequence = false; - this.CurrentSpanIndex = 0; - this.Consumed = 0; - this.memory = memory; - this.CurrentSpan = memory.Span; - this.length = memory.Length; - this.moreData = memory.Length > 0; - - this.currentPosition = default; - this.nextPosition = default; - this.sequence = default; - } - - /// - /// Gets a value indicating whether there is no more data in the . - /// - public bool End => !this.moreData; - - /// - /// Gets the underlying for the reader. - /// - public ReadOnlySequence Sequence - { - get - { - if (this.sequence.IsEmpty && !this.memory.IsEmpty) - { - // We're in memory mode (instead of sequence mode). - // Lazily fill in the sequence data. - this.sequence = new ReadOnlySequence(this.memory); - this.currentPosition = this.sequence.Start; - this.nextPosition = this.sequence.End; - } - - return this.sequence; - } - } - - /// - /// Gets the current position in the . - /// - public SequencePosition Position - => this.Sequence.GetPosition(this.CurrentSpanIndex, this.currentPosition); - - /// - /// Gets the current segment in the as a span. - /// - public ReadOnlySpan CurrentSpan { get; private set; } - - /// - /// Gets the index in the . - /// - public int CurrentSpanIndex { get; private set; } - - /// - /// Gets the unread portion of the . - /// - public ReadOnlySpan UnreadSpan - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => this.CurrentSpan.Slice(this.CurrentSpanIndex); - } - - /// - /// Gets the total number of 's processed by the reader. - /// - public long Consumed { get; private set; } - - /// - /// Gets remaining 's in the reader's . - /// - public long Remaining => this.Length - this.Consumed; - - /// - /// Gets count of in the reader's . - /// - public long Length - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if (this.length < 0) - { - // Cache the length - this.length = this.Sequence.Length; - } - - return this.length; - } - } - - /// - /// Peeks at the next value without advancing the reader. - /// - /// The next value or default if at the end. - /// False if at the end of the reader. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryPeek(out T value) - { - if (this.moreData) - { - value = this.CurrentSpan[this.CurrentSpanIndex]; - return true; - } - else - { - value = default; - return false; - } - } - - /// - /// Read the next value and advance the reader. - /// - /// The next value or default if at the end. - /// False if at the end of the reader. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryRead(out T value) - { - if (this.End) - { - value = default; - return false; - } - - value = this.CurrentSpan[this.CurrentSpanIndex]; - this.CurrentSpanIndex++; - this.Consumed++; - - if (this.CurrentSpanIndex >= this.CurrentSpan.Length) - { - if (this.usingSequence) - { - this.GetNextSpan(); - } - else - { - this.moreData = false; - } - } - - return true; - } - - /// - /// Move the reader back the specified number of items. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Rewind(long count) - { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - this.Consumed -= count; - - if (this.CurrentSpanIndex >= count) - { - this.CurrentSpanIndex -= (int)count; - this.moreData = true; - } - else if (this.usingSequence) - { - // Current segment doesn't have enough data, scan backward through segments - this.RetreatToPreviousSpan(this.Consumed); - } - else - { - throw new ArgumentOutOfRangeException("Rewind went past the start of the memory."); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private void RetreatToPreviousSpan(long consumed) - { - Debug.Assert(this.usingSequence, "usingSequence"); - this.ResetReader(); - this.Advance(consumed); - } - - private void ResetReader() - { - Debug.Assert(this.usingSequence, "usingSequence"); - this.CurrentSpanIndex = 0; - this.Consumed = 0; - this.currentPosition = this.Sequence.Start; - this.nextPosition = this.currentPosition; - - if (this.Sequence.TryGet(ref this.nextPosition, out ReadOnlyMemory memory, advance: true)) - { - this.moreData = true; - - if (memory.Length == 0) - { - this.CurrentSpan = default; - - // No data in the first span, move to one with data - this.GetNextSpan(); - } - else - { - this.CurrentSpan = memory.Span; - } - } - else - { - // No data in any spans and at end of sequence - this.moreData = false; - this.CurrentSpan = default; - } - } - - /// - /// Get the next segment with available data, if any. - /// - private void GetNextSpan() - { - Debug.Assert(this.usingSequence, "usingSequence"); - if (!this.Sequence.IsSingleSegment) - { - SequencePosition previousNextPosition = this.nextPosition; - while (this.Sequence.TryGet(ref this.nextPosition, out ReadOnlyMemory memory, advance: true)) - { - this.currentPosition = previousNextPosition; - if (memory.Length > 0) - { - this.CurrentSpan = memory.Span; - this.CurrentSpanIndex = 0; - return; - } - else - { - this.CurrentSpan = default; - this.CurrentSpanIndex = 0; - previousNextPosition = this.nextPosition; - } - } - } - - this.moreData = false; - } - - /// - /// Move the reader ahead the specified number of items. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Advance(long count) - { - const long TooBigOrNegative = unchecked((long)0xFFFFFFFF80000000); - if ((count & TooBigOrNegative) == 0 && this.CurrentSpan.Length - this.CurrentSpanIndex > (int)count) - { - this.CurrentSpanIndex += (int)count; - this.Consumed += count; - } - else if (this.usingSequence) - { - // Can't satisfy from the current span - this.AdvanceToNextSpan(count); - } - else if (this.CurrentSpan.Length - this.CurrentSpanIndex == (int)count) - { - this.CurrentSpanIndex += (int)count; - this.Consumed += count; - this.moreData = false; - } - else - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - } - - /// - /// Unchecked helper to avoid unnecessary checks where you know count is valid. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void AdvanceCurrentSpan(long count) - { - Debug.Assert(count >= 0, "count >= 0"); - - this.Consumed += count; - this.CurrentSpanIndex += (int)count; - if (this.usingSequence && this.CurrentSpanIndex >= this.CurrentSpan.Length) - { - this.GetNextSpan(); - } - } - - /// - /// Only call this helper if you know that you are advancing in the current span - /// with valid count and there is no need to fetch the next one. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void AdvanceWithinSpan(long count) - { - Debug.Assert(count >= 0, "count >= 0"); - - this.Consumed += count; - this.CurrentSpanIndex += (int)count; - - Debug.Assert(this.CurrentSpanIndex < this.CurrentSpan.Length, "this.CurrentSpanIndex < this.CurrentSpan.Length"); - } - - /// - /// Move the reader ahead the specified number of items - /// if there are enough elements remaining in the sequence. - /// - /// true if there were enough elements to advance; otherwise false. - internal bool TryAdvance(long count) - { - if (this.Remaining < count) - { - return false; - } - - this.Advance(count); - return true; - } - - private void AdvanceToNextSpan(long count) - { - Debug.Assert(this.usingSequence, "usingSequence"); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - this.Consumed += count; - while (this.moreData) - { - int remaining = this.CurrentSpan.Length - this.CurrentSpanIndex; - - if (remaining > count) - { - this.CurrentSpanIndex += (int)count; - count = 0; - break; - } - - // As there may not be any further segments we need to - // push the current index to the end of the span. - this.CurrentSpanIndex += remaining; - count -= remaining; - Debug.Assert(count >= 0, "count >= 0"); - - this.GetNextSpan(); - - if (count == 0) - { - break; - } - } - - if (count != 0) - { - // Not enough data left- adjust for where we actually ended and throw - this.Consumed -= count; - throw new ArgumentOutOfRangeException(nameof(count)); - } - } - - /// - /// Copies data from the current to the given span. - /// - /// Destination to copy to. - /// True if there is enough data to copy to the . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool TryCopyTo(Span destination) - { - ReadOnlySpan firstSpan = this.UnreadSpan; - if (firstSpan.Length >= destination.Length) - { - firstSpan.Slice(0, destination.Length).CopyTo(destination); - return true; - } - - return this.TryCopyMultisegment(destination); - } - - internal bool TryCopyMultisegment(Span destination) - { - if (this.Remaining < destination.Length) - { - return false; - } - - ReadOnlySpan firstSpan = this.UnreadSpan; - Debug.Assert(firstSpan.Length < destination.Length, "firstSpan.Length < destination.Length"); - firstSpan.CopyTo(destination); - int copied = firstSpan.Length; - - SequencePosition next = this.nextPosition; - while (this.Sequence.TryGet(ref next, out ReadOnlyMemory nextSegment, true)) - { - if (nextSegment.Length > 0) - { - ReadOnlySpan nextSpan = nextSegment.Span; - int toCopy = Math.Min(nextSpan.Length, destination.Length - copied); - nextSpan.Slice(0, toCopy).CopyTo(destination.Slice(copied)); - copied += toCopy; - if (copied >= destination.Length) - { - break; - } - } - } - - return true; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReader.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReader.cs.meta deleted file mode 100644 index 517c987..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 73a26645b66741b4081b24bbec4379c9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReaderExtensions.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReaderExtensions.cs deleted file mode 100644 index 9cfca50..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReaderExtensions.cs +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* Licensed to the .NET Foundation under one or more agreements. - * The .NET Foundation licenses this file to you under the MIT license. - * See the LICENSE file in the project root for more information. */ - -using System; -using System.Buffers.Binary; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace MessagePack -{ - internal static partial class SequenceReaderExtensions - { - /// - /// Try to read the given type out of the buffer if possible. Warning: this is dangerous to use with arbitrary - /// structs- see remarks for full details. - /// - /// - /// IMPORTANT: The read is a straight copy of bits. If a struct depends on specific state of its members to - /// behave correctly this can lead to exceptions, etc. If reading endian specific integers, use the explicit - /// overloads such as . - /// - /// - /// True if successful. will be default if failed (due to lack of space). - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static unsafe bool TryRead(ref this SequenceReader reader, out T value) - where T : unmanaged - { - ReadOnlySpan span = reader.UnreadSpan; - if (span.Length < sizeof(T)) - { - return TryReadMultisegment(ref reader, out value); - } - - value = Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(span)); - reader.Advance(sizeof(T)); - return true; - } - -#if UNITY_ANDROID - - /// - /// In Android 32bit device(armv7) + IL2CPP does not work correctly on Unsafe.ReadUnaligned. - /// Perhaps it is about memory alignment bug of Unity's IL2CPP VM. - /// For a workaround, read memory manually. - /// https://github.com/neuecc/MessagePack-CSharp/issues/748 - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static unsafe bool TryRead(ref this SequenceReader reader, out long value) - { - ReadOnlySpan span = reader.UnreadSpan; - if (span.Length < sizeof(long)) - { - return TryReadMultisegment(ref reader, out value); - } - - value = MessagePack.SafeBitConverter.ToInt64(span); - reader.Advance(sizeof(long)); - return true; - } - -#endif - - private static unsafe bool TryReadMultisegment(ref SequenceReader reader, out T value) - where T : unmanaged - { - Debug.Assert(reader.UnreadSpan.Length < sizeof(T), "reader.UnreadSpan.Length < sizeof(T)"); - - // Not enough data in the current segment, try to peek for the data we need. - T buffer = default; - Span tempSpan = new Span(&buffer, sizeof(T)); - - if (!reader.TryCopyTo(tempSpan)) - { - value = default; - return false; - } - - value = Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(tempSpan)); - reader.Advance(sizeof(T)); - return true; - } - -#if UNITY_ANDROID - - private static unsafe bool TryReadMultisegment(ref SequenceReader reader, out long value) - { - Debug.Assert(reader.UnreadSpan.Length < sizeof(long), "reader.UnreadSpan.Length < sizeof(long)"); - - // Not enough data in the current segment, try to peek for the data we need. - long buffer = default; - Span tempSpan = new Span(&buffer, sizeof(long)); - - if (!reader.TryCopyTo(tempSpan)) - { - value = default; - return false; - } - - value = MessagePack.SafeBitConverter.ToInt64(tempSpan); - reader.Advance(sizeof(long)); - return true; - } - -#endif - - /// - /// Reads an from the next position in the sequence. - /// - /// The reader to read from. - /// Receives the value read. - /// true if there was another byte in the sequence; false otherwise. - public static bool TryRead(ref this SequenceReader reader, out sbyte value) - { - if (TryRead(ref reader, out byte byteValue)) - { - value = unchecked((sbyte)byteValue); - return true; - } - - value = default; - return false; - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out short value) - { - if (!BitConverter.IsLittleEndian) - { - return reader.TryRead(out value); - } - - return TryReadReverseEndianness(ref reader, out value); - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out ushort value) - { - if (TryReadBigEndian(ref reader, out short shortValue)) - { - value = unchecked((ushort)shortValue); - return true; - } - - value = default; - return false; - } - - private static bool TryReadReverseEndianness(ref SequenceReader reader, out short value) - { - if (reader.TryRead(out value)) - { - value = BinaryPrimitives.ReverseEndianness(value); - return true; - } - - return false; - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out int value) - { - if (!BitConverter.IsLittleEndian) - { - return reader.TryRead(out value); - } - - return TryReadReverseEndianness(ref reader, out value); - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out uint value) - { - if (TryReadBigEndian(ref reader, out int intValue)) - { - value = unchecked((uint)intValue); - return true; - } - - value = default; - return false; - } - - private static bool TryReadReverseEndianness(ref SequenceReader reader, out int value) - { - if (reader.TryRead(out value)) - { - value = BinaryPrimitives.ReverseEndianness(value); - return true; - } - - return false; - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out long value) - { - if (!BitConverter.IsLittleEndian) - { - return reader.TryRead(out value); - } - - return TryReadReverseEndianness(ref reader, out value); - } - - /// - /// Reads an as big endian. - /// - /// False if there wasn't enough data for an . - public static bool TryReadBigEndian(ref this SequenceReader reader, out ulong value) - { - if (TryReadBigEndian(ref reader, out long longValue)) - { - value = unchecked((ulong)longValue); - return true; - } - - value = default; - return false; - } - - private static bool TryReadReverseEndianness(ref SequenceReader reader, out long value) - { - if (reader.TryRead(out value)) - { - value = BinaryPrimitives.ReverseEndianness(value); - return true; - } - - return false; - } - - /// - /// Reads a as big endian. - /// - /// False if there wasn't enough data for a . - public static unsafe bool TryReadBigEndian(ref this SequenceReader reader, out float value) - { - if (TryReadBigEndian(ref reader, out int intValue)) - { - value = *(float*)&intValue; - return true; - } - - value = default; - return false; - } - - /// - /// Reads a as big endian. - /// - /// False if there wasn't enough data for a . - public static unsafe bool TryReadBigEndian(ref this SequenceReader reader, out double value) - { - if (TryReadBigEndian(ref reader, out long longValue)) - { - value = *(double*)&longValue; - return true; - } - - value = default; - return false; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReaderExtensions.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReaderExtensions.cs.meta deleted file mode 100644 index b6af78d..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/SequenceReaderExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 74337ad77e62e5942b20dc45b62ddeab -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StreamPolyfillExtensions.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StreamPolyfillExtensions.cs deleted file mode 100644 index 2b6222c..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StreamPolyfillExtensions.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft; - -namespace MessagePack -{ -#if !SPAN_BUILTIN - internal static class StreamPolyfillExtensions - { - /// - /// Reads from the stream into a memory buffer. - /// - /// The stream to read from. - /// The buffer to read directly into. - /// The number of bytes actually read. - internal static int Read(this Stream stream, Span buffer) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - byte[] array = ArrayPool.Shared.Rent(buffer.Length); - try - { - int bytesRead = stream.Read(array, 0, buffer.Length); - new Span(array, 0, bytesRead).CopyTo(buffer); - return bytesRead; - } - finally - { - ArrayPool.Shared.Return(array); - } - } - - /// - /// Reads from the stream into a memory buffer. - /// - /// The stream to read from. - /// The buffer to read directly into. - /// A cancellation token. - /// The number of bytes actually read. - /// - /// This method shamelessly copied from the .NET Core 2.1 Stream class: https://github.com/dotnet/coreclr/blob/a113b1c803783c9d64f1f0e946ff9a853e3bc140/src/System.Private.CoreLib/shared/System/IO/Stream.cs#L366-L391. - /// - internal static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken = default) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (MemoryMarshal.TryGetArray(buffer, out ArraySegment array)) - { - return new ValueTask(stream.ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); - } - else - { - byte[] sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); - return FinishReadAsync(stream.ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer); - - async ValueTask FinishReadAsync(Task readTask, byte[] localBuffer, Memory localDestination) - { - try - { - int result = await readTask.ConfigureAwait(false); - new Span(localBuffer, 0, result).CopyTo(localDestination.Span); - return result; - } - finally - { - ArrayPool.Shared.Return(localBuffer); - } - } - } - } - - /// - /// Writes a span to the stream. - /// - /// The stream to write to. - /// The buffer to write. - internal static void Write(this Stream stream, ReadOnlySpan buffer) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - var sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); - try - { - buffer.CopyTo(sharedBuffer); - stream.Write(sharedBuffer, 0, buffer.Length); - } - finally - { - ArrayPool.Shared.Return(sharedBuffer); - } - } - - /// - /// Writes a span to the stream. - /// - /// The stream to write to. - /// The buffer to write. - /// A cancellation token. - internal static async ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - var sharedBuffer = ArrayPool.Shared.Rent(buffer.Length); - try - { - buffer.CopyTo(sharedBuffer); - await stream.WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); - } - finally - { - ArrayPool.Shared.Return(sharedBuffer); - } - } - } -#endif -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StreamPolyfillExtensions.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StreamPolyfillExtensions.cs.meta deleted file mode 100644 index abd0a78..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StreamPolyfillExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a129c39f0ce55af4fac3a1a6bcc1380e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StringEncoding.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StringEncoding.cs deleted file mode 100644 index 0be4214..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StringEncoding.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; - -namespace MessagePack -{ - internal static class StringEncoding - { - internal static readonly Encoding UTF8 = new UTF8Encoding(false); - -#if !NETCOREAPP // Define the extension method only where an instance method does not already exist. - internal static unsafe string GetString(this Encoding encoding, ReadOnlySpan bytes) - { - if (bytes.Length == 0) - { - return string.Empty; - } - - fixed (byte* pBytes = bytes) - { - return encoding.GetString(pBytes, bytes.Length); - } - } -#endif - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StringEncoding.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StringEncoding.cs.meta deleted file mode 100644 index aedc492..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/StringEncoding.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1d573b17dc675bc4482fbc3e79f86dca -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4.meta deleted file mode 100644 index bc63e80..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 87252c4dd4e93e740be6bd304eeeff16 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ForceSizePrimitiveFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ForceSizePrimitiveFormatter.cs deleted file mode 100644 index 1f91954..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ForceSizePrimitiveFormatter.cs +++ /dev/null @@ -1,814 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class ForceInt16BlockFormatter : IMessagePackFormatter - { - public static readonly ForceInt16BlockFormatter Instance = new ForceInt16BlockFormatter(); - - private ForceInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16 value, MessagePackSerializerOptions options) - { - writer.WriteInt16(value); - } - - public Int16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt16(); - } - } - - public sealed class NullableForceInt16BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceInt16BlockFormatter Instance = new NullableForceInt16BlockFormatter(); - - private NullableForceInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt16(value.Value); - } - } - - public Int16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt16(); - } - } - } - - public sealed class ForceInt16BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceInt16BlockArrayFormatter Instance = new ForceInt16BlockArrayFormatter(); - - private ForceInt16BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt16(value[i]); - } - } - } - - public Int16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Int16[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt16(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ForceInt32BlockFormatter : IMessagePackFormatter - { - public static readonly ForceInt32BlockFormatter Instance = new ForceInt32BlockFormatter(); - - private ForceInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32 value, MessagePackSerializerOptions options) - { - writer.WriteInt32(value); - } - - public Int32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt32(); - } - } - - public sealed class NullableForceInt32BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceInt32BlockFormatter Instance = new NullableForceInt32BlockFormatter(); - - private NullableForceInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt32(value.Value); - } - } - - public Int32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt32(); - } - } - } - - public sealed class ForceInt32BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceInt32BlockArrayFormatter Instance = new ForceInt32BlockArrayFormatter(); - - private ForceInt32BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt32(value[i]); - } - } - } - - public Int32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Int32[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt32(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ForceInt64BlockFormatter : IMessagePackFormatter - { - public static readonly ForceInt64BlockFormatter Instance = new ForceInt64BlockFormatter(); - - private ForceInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64 value, MessagePackSerializerOptions options) - { - writer.WriteInt64(value); - } - - public Int64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt64(); - } - } - - public sealed class NullableForceInt64BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceInt64BlockFormatter Instance = new NullableForceInt64BlockFormatter(); - - private NullableForceInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt64(value.Value); - } - } - - public Int64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt64(); - } - } - } - - public sealed class ForceInt64BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceInt64BlockArrayFormatter Instance = new ForceInt64BlockArrayFormatter(); - - private ForceInt64BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt64(value[i]); - } - } - } - - public Int64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Int64[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt64(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ForceUInt16BlockFormatter : IMessagePackFormatter - { - public static readonly ForceUInt16BlockFormatter Instance = new ForceUInt16BlockFormatter(); - - private ForceUInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16 value, MessagePackSerializerOptions options) - { - writer.WriteUInt16(value); - } - - public UInt16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt16(); - } - } - - public sealed class NullableForceUInt16BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceUInt16BlockFormatter Instance = new NullableForceUInt16BlockFormatter(); - - private NullableForceUInt16BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt16(value.Value); - } - } - - public UInt16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt16(); - } - } - } - - public sealed class ForceUInt16BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceUInt16BlockArrayFormatter Instance = new ForceUInt16BlockArrayFormatter(); - - private ForceUInt16BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteUInt16(value[i]); - } - } - } - - public UInt16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new UInt16[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt16(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ForceUInt32BlockFormatter : IMessagePackFormatter - { - public static readonly ForceUInt32BlockFormatter Instance = new ForceUInt32BlockFormatter(); - - private ForceUInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32 value, MessagePackSerializerOptions options) - { - writer.WriteUInt32(value); - } - - public UInt32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt32(); - } - } - - public sealed class NullableForceUInt32BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceUInt32BlockFormatter Instance = new NullableForceUInt32BlockFormatter(); - - private NullableForceUInt32BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt32(value.Value); - } - } - - public UInt32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt32(); - } - } - } - - public sealed class ForceUInt32BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceUInt32BlockArrayFormatter Instance = new ForceUInt32BlockArrayFormatter(); - - private ForceUInt32BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteUInt32(value[i]); - } - } - } - - public UInt32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new UInt32[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt32(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ForceUInt64BlockFormatter : IMessagePackFormatter - { - public static readonly ForceUInt64BlockFormatter Instance = new ForceUInt64BlockFormatter(); - - private ForceUInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64 value, MessagePackSerializerOptions options) - { - writer.WriteUInt64(value); - } - - public UInt64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt64(); - } - } - - public sealed class NullableForceUInt64BlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceUInt64BlockFormatter Instance = new NullableForceUInt64BlockFormatter(); - - private NullableForceUInt64BlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt64(value.Value); - } - } - - public UInt64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt64(); - } - } - } - - public sealed class ForceUInt64BlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceUInt64BlockArrayFormatter Instance = new ForceUInt64BlockArrayFormatter(); - - private ForceUInt64BlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteUInt64(value[i]); - } - } - } - - public UInt64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new UInt64[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt64(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } - - public sealed class ForceByteBlockFormatter : IMessagePackFormatter - { - public static readonly ForceByteBlockFormatter Instance = new ForceByteBlockFormatter(); - - private ForceByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte value, MessagePackSerializerOptions options) - { - writer.WriteUInt8(value); - } - - public Byte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadByte(); - } - } - - public sealed class NullableForceByteBlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceByteBlockFormatter Instance = new NullableForceByteBlockFormatter(); - - private NullableForceByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteUInt8(value.Value); - } - } - - public Byte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadByte(); - } - } - } - - public sealed class ForceSByteBlockFormatter : IMessagePackFormatter - { - public static readonly ForceSByteBlockFormatter Instance = new ForceSByteBlockFormatter(); - - private ForceSByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte value, MessagePackSerializerOptions options) - { - writer.WriteInt8(value); - } - - public SByte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadSByte(); - } - } - - public sealed class NullableForceSByteBlockFormatter : IMessagePackFormatter - { - public static readonly NullableForceSByteBlockFormatter Instance = new NullableForceSByteBlockFormatter(); - - private NullableForceSByteBlockFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteInt8(value.Value); - } - } - - public SByte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadSByte(); - } - } - } - - public sealed class ForceSByteBlockArrayFormatter : IMessagePackFormatter - { - public static readonly ForceSByteBlockArrayFormatter Instance = new ForceSByteBlockArrayFormatter(); - - private ForceSByteBlockArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.WriteInt8(value[i]); - } - } - } - - public SByte[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new SByte[len]; - options.Security.DepthStep(ref reader); - try - { - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadSByte(); - } - } - finally - { - reader.Depth--; - } - - return array; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ForceSizePrimitiveFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ForceSizePrimitiveFormatter.cs.meta deleted file mode 100644 index d9d66b8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ForceSizePrimitiveFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1ad9a757f1a235248aace5bb771bb786 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/MessagePackReader.Integers.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/MessagePackReader.Integers.cs deleted file mode 100644 index d74c394..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/MessagePackReader.Integers.cs +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -namespace MessagePack -{ -#pragma warning disable SA1205 // Partial elements should declare access - ref partial struct MessagePackReader -#pragma warning restore SA1205 // Partial elements should declare access - { - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Byte ReadByte() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Byte)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Byte)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Byte)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Byte)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Byte)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Byte)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Byte)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Byte)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Byte)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Byte)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public UInt16 ReadUInt16() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((UInt16)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((UInt16)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((UInt16)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((UInt16)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((UInt16)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((UInt16)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((UInt16)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((UInt16)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((UInt16)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (UInt16)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public UInt32 ReadUInt32() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((UInt32)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((UInt32)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((UInt32)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((UInt32)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((UInt32)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((UInt32)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((UInt32)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((UInt32)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((UInt32)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (UInt32)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public UInt64 ReadUInt64() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((UInt64)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((UInt64)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((UInt64)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((UInt64)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((UInt64)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((UInt64)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((UInt64)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((UInt64)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((UInt64)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (UInt64)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public SByte ReadSByte() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((SByte)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((SByte)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((SByte)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((SByte)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((SByte)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((SByte)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((SByte)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((SByte)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((SByte)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (SByte)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Int16 ReadInt16() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Int16)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Int16)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Int16)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Int16)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Int16)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Int16)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Int16)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Int16)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Int16)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Int16)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Int32 ReadInt32() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Int32)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Int32)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Int32)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Int32)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Int32)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Int32)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Int32)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Int32)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Int32)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Int32)code; - } - - throw ThrowInvalidCode(code); - } - } - - /// - /// Reads an value from: - /// Some value between and , - /// Some value between and , - /// or any of the other MsgPack integer types. - /// - /// The value. - /// Thrown when the value exceeds what can be stored in the returned type. - public Int64 ReadInt64() - { - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte code)); - - switch (code) - { - case MessagePackCode.UInt8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out byte byteResult)); - return checked((Int64)byteResult); - case MessagePackCode.Int8: - ThrowInsufficientBufferUnless(this.reader.TryRead(out sbyte sbyteResult)); - return checked((Int64)sbyteResult); - case MessagePackCode.UInt16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ushort ushortResult)); - return checked((Int64)ushortResult); - case MessagePackCode.Int16: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out short shortResult)); - return checked((Int64)shortResult); - case MessagePackCode.UInt32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out uint uintResult)); - return checked((Int64)uintResult); - case MessagePackCode.Int32: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out int intResult)); - return checked((Int64)intResult); - case MessagePackCode.UInt64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out ulong ulongResult)); - return checked((Int64)ulongResult); - case MessagePackCode.Int64: - ThrowInsufficientBufferUnless(this.reader.TryReadBigEndian(out long longResult)); - return checked((Int64)longResult); - default: - if (code >= MessagePackCode.MinNegativeFixInt && code <= MessagePackCode.MaxNegativeFixInt) - { - return checked((Int64)unchecked((sbyte)code)); - } - - if (code >= MessagePackCode.MinFixInt && code <= MessagePackCode.MaxFixInt) - { - return (Int64)code; - } - - throw ThrowInvalidCode(code); - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/MessagePackReader.Integers.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/MessagePackReader.Integers.cs.meta deleted file mode 100644 index a871ad1..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/MessagePackReader.Integers.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d034a54b76ed3944da5cd3666462e89e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/PrimitiveFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/PrimitiveFormatter.cs deleted file mode 100644 index aac69b6..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/PrimitiveFormatter.cs +++ /dev/null @@ -1,1253 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class Int16Formatter : IMessagePackFormatter - { - public static readonly Int16Formatter Instance = new Int16Formatter(); - - private Int16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Int16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt16(); - } - } - - public sealed class NullableInt16Formatter : IMessagePackFormatter - { - public static readonly NullableInt16Formatter Instance = new NullableInt16Formatter(); - - private NullableInt16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Int16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt16(); - } - } - } - - public sealed class Int16ArrayFormatter : IMessagePackFormatter - { - public static readonly Int16ArrayFormatter Instance = new Int16ArrayFormatter(); - - private Int16ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Int16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Int16[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt16(); - } - - return array; - } - } - - public sealed class Int32Formatter : IMessagePackFormatter - { - public static readonly Int32Formatter Instance = new Int32Formatter(); - - private Int32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Int32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt32(); - } - } - - public sealed class NullableInt32Formatter : IMessagePackFormatter - { - public static readonly NullableInt32Formatter Instance = new NullableInt32Formatter(); - - private NullableInt32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Int32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt32(); - } - } - } - - public sealed class Int32ArrayFormatter : IMessagePackFormatter - { - public static readonly Int32ArrayFormatter Instance = new Int32ArrayFormatter(); - - private Int32ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Int32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Int32[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt32(); - } - - return array; - } - } - - public sealed class Int64Formatter : IMessagePackFormatter - { - public static readonly Int64Formatter Instance = new Int64Formatter(); - - private Int64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Int64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadInt64(); - } - } - - public sealed class NullableInt64Formatter : IMessagePackFormatter - { - public static readonly NullableInt64Formatter Instance = new NullableInt64Formatter(); - - private NullableInt64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Int64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadInt64(); - } - } - } - - public sealed class Int64ArrayFormatter : IMessagePackFormatter - { - public static readonly Int64ArrayFormatter Instance = new Int64ArrayFormatter(); - - private Int64ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Int64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Int64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Int64[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadInt64(); - } - - return array; - } - } - - public sealed class UInt16Formatter : IMessagePackFormatter - { - public static readonly UInt16Formatter Instance = new UInt16Formatter(); - - private UInt16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public UInt16 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt16(); - } - } - - public sealed class NullableUInt16Formatter : IMessagePackFormatter - { - public static readonly NullableUInt16Formatter Instance = new NullableUInt16Formatter(); - - private NullableUInt16Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public UInt16? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt16(); - } - } - } - - public sealed class UInt16ArrayFormatter : IMessagePackFormatter - { - public static readonly UInt16ArrayFormatter Instance = new UInt16ArrayFormatter(); - - private UInt16ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt16[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public UInt16[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new UInt16[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt16(); - } - - return array; - } - } - - public sealed class UInt32Formatter : IMessagePackFormatter - { - public static readonly UInt32Formatter Instance = new UInt32Formatter(); - - private UInt32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public UInt32 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt32(); - } - } - - public sealed class NullableUInt32Formatter : IMessagePackFormatter - { - public static readonly NullableUInt32Formatter Instance = new NullableUInt32Formatter(); - - private NullableUInt32Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public UInt32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt32(); - } - } - } - - public sealed class UInt32ArrayFormatter : IMessagePackFormatter - { - public static readonly UInt32ArrayFormatter Instance = new UInt32ArrayFormatter(); - - private UInt32ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt32[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public UInt32[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new UInt32[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt32(); - } - - return array; - } - } - - public sealed class UInt64Formatter : IMessagePackFormatter - { - public static readonly UInt64Formatter Instance = new UInt64Formatter(); - - private UInt64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64 value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public UInt64 Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadUInt64(); - } - } - - public sealed class NullableUInt64Formatter : IMessagePackFormatter - { - public static readonly NullableUInt64Formatter Instance = new NullableUInt64Formatter(); - - private NullableUInt64Formatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public UInt64? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadUInt64(); - } - } - } - - public sealed class UInt64ArrayFormatter : IMessagePackFormatter - { - public static readonly UInt64ArrayFormatter Instance = new UInt64ArrayFormatter(); - - private UInt64ArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, UInt64[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public UInt64[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new UInt64[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadUInt64(); - } - - return array; - } - } - - public sealed class SingleFormatter : IMessagePackFormatter - { - public static readonly SingleFormatter Instance = new SingleFormatter(); - - private SingleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Single value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Single Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadSingle(); - } - } - - public sealed class NullableSingleFormatter : IMessagePackFormatter - { - public static readonly NullableSingleFormatter Instance = new NullableSingleFormatter(); - - private NullableSingleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Single? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Single? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadSingle(); - } - } - } - - public sealed class SingleArrayFormatter : IMessagePackFormatter - { - public static readonly SingleArrayFormatter Instance = new SingleArrayFormatter(); - - private SingleArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Single[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Single[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Single[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadSingle(); - } - - return array; - } - } - - public sealed class DoubleFormatter : IMessagePackFormatter - { - public static readonly DoubleFormatter Instance = new DoubleFormatter(); - - private DoubleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Double value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Double Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadDouble(); - } - } - - public sealed class NullableDoubleFormatter : IMessagePackFormatter - { - public static readonly NullableDoubleFormatter Instance = new NullableDoubleFormatter(); - - private NullableDoubleFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Double? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Double? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadDouble(); - } - } - } - - public sealed class DoubleArrayFormatter : IMessagePackFormatter - { - public static readonly DoubleArrayFormatter Instance = new DoubleArrayFormatter(); - - private DoubleArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Double[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Double[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Double[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadDouble(); - } - - return array; - } - } - - public sealed class BooleanFormatter : IMessagePackFormatter - { - public static readonly BooleanFormatter Instance = new BooleanFormatter(); - - private BooleanFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Boolean value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Boolean Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadBoolean(); - } - } - - public sealed class NullableBooleanFormatter : IMessagePackFormatter - { - public static readonly NullableBooleanFormatter Instance = new NullableBooleanFormatter(); - - private NullableBooleanFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Boolean? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Boolean? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadBoolean(); - } - } - } - - public sealed class BooleanArrayFormatter : IMessagePackFormatter - { - public static readonly BooleanArrayFormatter Instance = new BooleanArrayFormatter(); - - private BooleanArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Boolean[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Boolean[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Boolean[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadBoolean(); - } - - return array; - } - } - - public sealed class ByteFormatter : IMessagePackFormatter - { - public static readonly ByteFormatter Instance = new ByteFormatter(); - - private ByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Byte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadByte(); - } - } - - public sealed class NullableByteFormatter : IMessagePackFormatter - { - public static readonly NullableByteFormatter Instance = new NullableByteFormatter(); - - private NullableByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Byte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Byte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadByte(); - } - } - } - - public sealed class SByteFormatter : IMessagePackFormatter - { - public static readonly SByteFormatter Instance = new SByteFormatter(); - - private SByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public SByte Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadSByte(); - } - } - - public sealed class NullableSByteFormatter : IMessagePackFormatter - { - public static readonly NullableSByteFormatter Instance = new NullableSByteFormatter(); - - private NullableSByteFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public SByte? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadSByte(); - } - } - } - - public sealed class SByteArrayFormatter : IMessagePackFormatter - { - public static readonly SByteArrayFormatter Instance = new SByteArrayFormatter(); - - private SByteArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, SByte[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public SByte[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new SByte[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadSByte(); - } - - return array; - } - } - - public sealed class CharFormatter : IMessagePackFormatter - { - public static readonly CharFormatter Instance = new CharFormatter(); - - private CharFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Char value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public Char Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadChar(); - } - } - - public sealed class NullableCharFormatter : IMessagePackFormatter - { - public static readonly NullableCharFormatter Instance = new NullableCharFormatter(); - - private NullableCharFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Char? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public Char? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadChar(); - } - } - } - - public sealed class CharArrayFormatter : IMessagePackFormatter - { - public static readonly CharArrayFormatter Instance = new CharArrayFormatter(); - - private CharArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, Char[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public Char[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new Char[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadChar(); - } - - return array; - } - } - - public sealed class DateTimeFormatter : IMessagePackFormatter - { - public static readonly DateTimeFormatter Instance = new DateTimeFormatter(); - - private DateTimeFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTime value, MessagePackSerializerOptions options) - { - writer.Write(value); - } - - public DateTime Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - return reader.ReadDateTime(); - } - } - - public sealed class NullableDateTimeFormatter : IMessagePackFormatter - { - public static readonly NullableDateTimeFormatter Instance = new NullableDateTimeFormatter(); - - private NullableDateTimeFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTime? value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.Write(value.Value); - } - } - - public DateTime? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - return reader.ReadDateTime(); - } - } - } - - public sealed class DateTimeArrayFormatter : IMessagePackFormatter - { - public static readonly DateTimeArrayFormatter Instance = new DateTimeArrayFormatter(); - - private DateTimeArrayFormatter() - { - } - - public void Serialize(ref MessagePackWriter writer, DateTime[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(value.Length); - for (int i = 0; i < value.Length; i++) - { - writer.Write(value[i]); - } - } - } - - public DateTime[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - - var len = reader.ReadArrayHeader(); - if (len == 0) - { - return Array.Empty(); - } - - var array = new DateTime[len]; - for (int i = 0; i < array.Length; i++) - { - array[i] = reader.ReadDateTime(); - } - - return array; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/PrimitiveFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/PrimitiveFormatter.cs.meta deleted file mode 100644 index 9b4c790..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/PrimitiveFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eb48ea027ca8fa84c8677fac8791b318 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/TupleFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/TupleFormatter.cs deleted file mode 100644 index e9a1741..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/TupleFormatter.cs +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(1); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 1) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(2); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 2) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(3); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 3) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(4); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 4) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(5); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 5) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(6); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 6) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5, item6); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(7); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 7) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5, item6, item7); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class TupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, Tuple value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - } - else - { - writer.WriteArrayHeader(8); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Rest, options); - } - } - - public Tuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return default; - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 8) - { - throw new MessagePackSerializationException("Invalid Tuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - TRest item8 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new Tuple(item1, item2, item3, item4, item5, item6, item7, item8); - } - finally - { - reader.Depth--; - } - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/TupleFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/TupleFormatter.cs.meta deleted file mode 100644 index c0c5539..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/TupleFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6b14afc37320aee4daaa80c6b1e6529f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/UnsafeMemory.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/UnsafeMemory.cs deleted file mode 100644 index d986575..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/UnsafeMemory.cs +++ /dev/null @@ -1,901 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -#if !UNITY_2018_3_OR_NEWER - -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using MessagePack.Formatters; - -namespace MessagePack.Internal -{ - public static partial class UnsafeMemory32 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw4(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw5(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 1) = *(int*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw6(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 2) = *(int*)(pSrc + 2); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw7(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 3) = *(int*)(pSrc + 3); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw8(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw9(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 5) = *(int*)(pSrc + 5); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw10(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 6) = *(int*)(pSrc + 6); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw11(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 7) = *(int*)(pSrc + 7); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw12(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw13(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 9) = *(int*)(pSrc + 9); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw14(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 10) = *(int*)(pSrc + 10); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw15(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 11) = *(int*)(pSrc + 11); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw16(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw17(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 13) = *(int*)(pSrc + 13); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw18(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 14) = *(int*)(pSrc + 14); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw19(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 15) = *(int*)(pSrc + 15); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw20(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw21(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 17) = *(int*)(pSrc + 17); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw22(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 18) = *(int*)(pSrc + 18); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw23(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 19) = *(int*)(pSrc + 19); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw24(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw25(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 21) = *(int*)(pSrc + 21); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw26(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 22) = *(int*)(pSrc + 22); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw27(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 23) = *(int*)(pSrc + 23); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw28(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw29(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - *(int*)(pDst + 25) = *(int*)(pSrc + 25); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw30(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - *(int*)(pDst + 26) = *(int*)(pSrc + 26); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw31(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(int*)(pDst + 0) = *(int*)(pSrc + 0); - *(int*)(pDst + 4) = *(int*)(pSrc + 4); - *(int*)(pDst + 8) = *(int*)(pSrc + 8); - *(int*)(pDst + 12) = *(int*)(pSrc + 12); - *(int*)(pDst + 16) = *(int*)(pSrc + 16); - *(int*)(pDst + 20) = *(int*)(pSrc + 20); - *(int*)(pDst + 24) = *(int*)(pSrc + 24); - *(int*)(pDst + 27) = *(int*)(pSrc + 27); - } - - writer.Advance(src.Length); - } - } - - public static partial class UnsafeMemory64 - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw8(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw9(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 1) = *(long*)(pSrc + 1); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw10(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 2) = *(long*)(pSrc + 2); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw11(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 3) = *(long*)(pSrc + 3); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw12(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 4) = *(long*)(pSrc + 4); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw13(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 5) = *(long*)(pSrc + 5); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw14(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 6) = *(long*)(pSrc + 6); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw15(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 7) = *(long*)(pSrc + 7); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw16(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw17(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 9) = *(long*)(pSrc + 9); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw18(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 10) = *(long*)(pSrc + 10); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw19(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 11) = *(long*)(pSrc + 11); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw20(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 12) = *(long*)(pSrc + 12); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw21(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 13) = *(long*)(pSrc + 13); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw22(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 14) = *(long*)(pSrc + 14); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw23(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 15) = *(long*)(pSrc + 15); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw24(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw25(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 17) = *(long*)(pSrc + 17); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw26(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 18) = *(long*)(pSrc + 18); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw27(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 19) = *(long*)(pSrc + 19); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw28(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 20) = *(long*)(pSrc + 20); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw29(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 21) = *(long*)(pSrc + 21); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw30(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 22) = *(long*)(pSrc + 22); - } - - writer.Advance(src.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe void WriteRaw31(ref MessagePackWriter writer, ReadOnlySpan src) - { - Span dst = writer.GetSpan(src.Length); - - fixed (byte* pSrc = &src[0]) - fixed (byte* pDst = &dst[0]) - { - *(long*)(pDst + 0) = *(long*)(pSrc + 0); - *(long*)(pDst + 8) = *(long*)(pSrc + 8); - *(long*)(pDst + 16) = *(long*)(pSrc + 16); - *(long*)(pDst + 23) = *(long*)(pSrc + 23); - } - - writer.Advance(src.Length); - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/UnsafeMemory.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/UnsafeMemory.cs.meta deleted file mode 100644 index e70a5c2..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/UnsafeMemory.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 50b6bcd206242f944833ba2d0548b028 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ValueTupleFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ValueTupleFormatter.cs deleted file mode 100644 index cf78e8b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ValueTupleFormatter.cs +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -/* THIS (.cs) FILE IS GENERATED. DO NOT CHANGE IT. - * CHANGE THE .tt FILE INSTEAD. */ - -using System; -using System.Buffers; - -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters -{ - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(1); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 1) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 2) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(3); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 3) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 4) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(5); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 5) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(6); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 6) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5, item6); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(7); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 7) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5, item6, item7); - } - finally - { - reader.Depth--; - } - } - } - } - - public sealed class ValueTupleFormatter : IMessagePackFormatter> - where TRest : struct - { - public void Serialize(ref MessagePackWriter writer, ValueTuple value, MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(8); - - IFormatterResolver resolver = options.Resolver; - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item1, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item2, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item3, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item4, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item5, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item6, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Item7, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.Rest, options); - } - - public ValueTuple Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new MessagePackSerializationException("Data is Nil, ValueTuple can not be null."); - } - else - { - var count = reader.ReadArrayHeader(); - if (count != 8) - { - throw new MessagePackSerializationException("Invalid ValueTuple count"); - } - - IFormatterResolver resolver = options.Resolver; - options.Security.DepthStep(ref reader); - try - { - T1 item1 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T2 item2 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T3 item3 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T4 item4 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T5 item5 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T6 item6 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - T7 item7 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - TRest item8 = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - - return new ValueTuple(item1, item2, item3, item4, item5, item6, item7, item8); - } - finally - { - reader.Depth--; - } - } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ValueTupleFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ValueTupleFormatter.cs.meta deleted file mode 100644 index 1d29a9b..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/T4/ValueTupleFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 98e54c0165ce30446938aa828e753eb5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ThisLibraryExtensionTypeCodes.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ThisLibraryExtensionTypeCodes.cs deleted file mode 100644 index a9620bd..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ThisLibraryExtensionTypeCodes.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace MessagePack -{ - /// - /// The extension type codes that this library defines for just this library. - /// - internal static class ThisLibraryExtensionTypeCodes - { - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityVector2 = 30; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityVector3 = 31; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityVector4 = 32; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityQuaternion = 33; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityColor = 34; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityBounds = 35; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityRect = 36; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityInt = 37; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityFloat = 38; - - /// - /// For Unity's UnsafeBlitFormatter. - /// - internal const sbyte UnityDouble = 39; - - /// - /// The LZ4 array block compression extension. - /// - internal const sbyte Lz4BlockArray = 98; - - /// - /// The LZ4 single block compression extension. - /// - internal const sbyte Lz4Block = 99; - - /// - /// For the . - /// - internal const sbyte TypelessFormatter = 100; - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ThisLibraryExtensionTypeCodes.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ThisLibraryExtensionTypeCodes.cs.meta deleted file mode 100644 index 1d02ac9..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/ThisLibraryExtensionTypeCodes.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1d1907f02cbdd5942a88a8770336fe7e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity.meta deleted file mode 100644 index ad8e91a..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 92b69c557585807449e9b4a38f5c1d27 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension.meta deleted file mode 100644 index 8745d4f..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 7251034389585f04e84fcb2595079ab3 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs deleted file mode 100644 index f846da8..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using UnityEngine; - -namespace MessagePack.Unity.Extension -{ - /// - /// Special Resolver for Vector2[], Vector3[], Vector4[], Quaternion[], Color[], Bounds[], Rect[]. - /// - public class UnityBlitResolver : IFormatterResolver - { - public static readonly UnityBlitResolver Instance = new UnityBlitResolver(); - - private UnityBlitResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)UnityBlitResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } - - /// - /// Special Resolver for Vector2[], Vector3[], Vector4[], Quaternion[], Color[], Bounds[], Rect[] + int[], float[], double[]. - /// - public class UnityBlitWithPrimitiveArrayResolver : IFormatterResolver - { - public static readonly UnityBlitWithPrimitiveArrayResolver Instance = new UnityBlitWithPrimitiveArrayResolver(); - - private UnityBlitWithPrimitiveArrayResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)UnityBlitWithPrimitiveResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (Formatter == null) - { - Formatter = UnityBlitResolver.Instance.GetFormatter(); - } - } - } - } - - internal static class UnityBlitResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(Vector2[]), typeof(Vector2ArrayBlitFormatter) }, - { typeof(Vector3[]), typeof(Vector3ArrayBlitFormatter) }, - { typeof(Vector4[]), typeof(Vector4ArrayBlitFormatter) }, - { typeof(Quaternion[]), typeof(QuaternionArrayBlitFormatter) }, - { typeof(Color[]), typeof(ColorArrayBlitFormatter) }, - { typeof(Bounds[]), typeof(BoundsArrayBlitFormatter) }, - { typeof(Rect[]), typeof(RectArrayBlitFormatter) }, - }; - - internal static object GetFormatter(Type t) - { - Type formatterType; - if (FormatterMap.TryGetValue(t, out formatterType)) - { - return Activator.CreateInstance(formatterType); - } - - return null; - } - } - - internal static class UnityBlitWithPrimitiveResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - { typeof(int[]), typeof(IntArrayBlitFormatter) }, - { typeof(float[]), typeof(FloatArrayBlitFormatter) }, - { typeof(double[]), typeof(DoubleArrayBlitFormatter) }, - }; - - internal static object GetFormatter(Type t) - { - Type formatterType; - if (FormatterMap.TryGetValue(t, out formatterType)) - { - return Activator.CreateInstance(formatterType); - } - - return null; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs.meta deleted file mode 100644 index 463d99e..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2780e6c52e347c540a336113d4a61fd3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs deleted file mode 100644 index 3682b03..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; -using MessagePack.Formatters; -using UnityEngine; - -#pragma warning disable SA1402 // multiple types in a file -#pragma warning disable SA1649 // file name matches type name - -namespace MessagePack.Unity.Extension -{ - // use ext instead of ArrayFormatter to extremely boost up performance. - // Layout: [extHeader, byteSize(integer), isLittleEndian(bool), bytes()] - // Used Ext:30~36 - public abstract class UnsafeBlitFormatterBase : IMessagePackFormatter - where T : struct - { - protected abstract sbyte TypeCode { get; } - - protected void CopyDeserializeUnsafe(ReadOnlySpan src, Span dest) => src.CopyTo(MemoryMarshal.Cast(dest)); - - public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - var byteLen = value.Length * Marshal.SizeOf(); - - writer.WriteExtensionFormatHeader(new ExtensionHeader(this.TypeCode, byteLen)); - writer.Write(byteLen); // write original header(not array header) - writer.Write(BitConverter.IsLittleEndian); - writer.WriteRaw(MemoryMarshal.Cast(value)); - } - - public T[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - ExtensionHeader header = reader.ReadExtensionFormatHeader(); - if (header.TypeCode != this.TypeCode) - { - throw new InvalidOperationException("Invalid typeCode."); - } - - var byteLength = reader.ReadInt32(); - var isLittleEndian = reader.ReadBoolean(); - - // Allocate a T[] that we will return. We'll then cast the T[] as byte[] so we can copy the byte sequence directly into it. - var result = new T[byteLength / Marshal.SizeOf()]; - Span resultAsBytes = MemoryMarshal.Cast(result); - reader.ReadRaw(byteLength).CopyTo(resultAsBytes); - - // Reverse the byte order if necessary. - if (isLittleEndian != BitConverter.IsLittleEndian) - { - for (int i = 0, j = resultAsBytes.Length - 1; i < j; i++, j--) - { - byte tmp = resultAsBytes[i]; - resultAsBytes[i] = resultAsBytes[j]; - resultAsBytes[j] = tmp; - } - } - - return result; - } - } - - public class Vector2ArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityVector2; - } - } - } - - public class Vector3ArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityVector3; - } - } - } - - public class Vector4ArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityVector4; - } - } - } - - public class QuaternionArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityQuaternion; - } - } - } - - public class ColorArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityColor; - } - } - } - - public class BoundsArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityBounds; - } - } - } - - public class RectArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get - { - return ThisLibraryExtensionTypeCodes.UnityRect; - } - } - } - - public class IntArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get { return ThisLibraryExtensionTypeCodes.UnityInt; } - } - } - - public class FloatArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get { return ThisLibraryExtensionTypeCodes.UnityFloat; } - } - } - - public class DoubleArrayBlitFormatter : UnsafeBlitFormatterBase - { - protected override sbyte TypeCode - { - get { return ThisLibraryExtensionTypeCodes.UnityDouble; } - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs.meta deleted file mode 100644 index 069b428..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 314e1d2058a6e9d4297aa329b34150d3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Formatters.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Formatters.cs deleted file mode 100644 index e3b0876..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Formatters.cs +++ /dev/null @@ -1,1135 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; -using MessagePack; -using MessagePack.Formatters; - -#pragma warning disable SA1312 // variable naming -#pragma warning disable SA1402 // one type per file -#pragma warning disable SA1649 // file name matches type name - -namespace MessagePack.Unity -{ - public sealed class Vector2Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector2 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(value.x); - writer.Write(value.y); - } - - public global::UnityEngine.Vector2 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Vector2(x, y); - return result; - } - } - - public sealed class Vector3Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(3); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.z); - } - - public global::UnityEngine.Vector3 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var z = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - z = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Vector3(x, y, z); - return result; - } - } - - public sealed class Vector4Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector4 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.z); - writer.Write(value.w); - } - - public global::UnityEngine.Vector4 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var z = default(float); - var w = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - z = reader.ReadSingle(); - break; - case 3: - w = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Vector4(x, y, z, w); - return result; - } - } - - public sealed class QuaternionFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Quaternion value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.z); - writer.Write(value.w); - } - - public global::UnityEngine.Quaternion Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var z = default(float); - var w = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - z = reader.ReadSingle(); - break; - case 3: - w = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Quaternion(x, y, z, w); - return result; - } - } - - public sealed class ColorFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Color value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.r); - writer.Write(value.g); - writer.Write(value.b); - writer.Write(value.a); - } - - public global::UnityEngine.Color Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var r = default(float); - var g = default(float); - var b = default(float); - var a = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - r = reader.ReadSingle(); - break; - case 1: - g = reader.ReadSingle(); - break; - case 2: - b = reader.ReadSingle(); - break; - case 3: - a = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Color(r, g, b, a); - return result; - } - } - - public sealed class BoundsFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Bounds value, global::MessagePack.MessagePackSerializerOptions options) - { - IFormatterResolver resolver = options.Resolver; - writer.WriteArrayHeader(2); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.center, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.size, options); - } - - public global::UnityEngine.Bounds Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - IFormatterResolver resolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var center = default(global::UnityEngine.Vector3); - var size = default(global::UnityEngine.Vector3); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - center = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - size = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Bounds(center, size); - return result; - } - } - - public sealed class RectFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Rect value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.x); - writer.Write(value.y); - writer.Write(value.width); - writer.Write(value.height); - } - - public global::UnityEngine.Rect Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var x = default(float); - var y = default(float); - var width = default(float); - var height = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - x = reader.ReadSingle(); - break; - case 1: - y = reader.ReadSingle(); - break; - case 2: - width = reader.ReadSingle(); - break; - case 3: - height = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var result = new global::UnityEngine.Rect(x, y, width, height); - return result; - } - } - - // additional - public sealed class WrapModeFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.WrapMode value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.Write((int)value); - } - - public global::UnityEngine.WrapMode Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - return (global::UnityEngine.WrapMode)reader.ReadInt32(); - } - } - - public sealed class GradientModeFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.GradientMode value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.Write((int)value); - } - - public global::UnityEngine.GradientMode Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - return (global::UnityEngine.GradientMode)reader.ReadInt32(); - } - } - - public sealed class KeyframeFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Keyframe value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.time); - writer.Write(value.value); - writer.Write(value.inTangent); - writer.Write(value.outTangent); - } - - public global::UnityEngine.Keyframe Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __time__ = default(float); - var __value__ = default(float); - var __inTangent__ = default(float); - var __outTangent__ = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __time__ = reader.ReadSingle(); - break; - case 1: - __value__ = reader.ReadSingle(); - break; - case 2: - __inTangent__ = reader.ReadSingle(); - break; - case 3: - __outTangent__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Keyframe(__time__, __value__, __inTangent__, __outTangent__); - ____result.time = __time__; - ____result.value = __value__; - ____result.inTangent = __inTangent__; - ____result.outTangent = __outTangent__; - return ____result; - } - } - - public sealed class AnimationCurveFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.AnimationCurve value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver resolver = options.Resolver; - writer.WriteArrayHeader(3); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.keys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.postWrapMode, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.preWrapMode, options); - } - - public global::UnityEngine.AnimationCurve Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; - } - - IFormatterResolver resolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var __keys__ = default(global::UnityEngine.Keyframe[]); - var __postWrapMode__ = default(global::UnityEngine.WrapMode); - var __preWrapMode__ = default(global::UnityEngine.WrapMode); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __keys__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __postWrapMode__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __preWrapMode__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.AnimationCurve(); - ____result.keys = __keys__; - ____result.postWrapMode = __postWrapMode__; - ____result.preWrapMode = __preWrapMode__; - return ____result; - } - } - - public sealed class Matrix4x4Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Matrix4x4 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(16); - writer.Write(value.m00); - writer.Write(value.m10); - writer.Write(value.m20); - writer.Write(value.m30); - writer.Write(value.m01); - writer.Write(value.m11); - writer.Write(value.m21); - writer.Write(value.m31); - writer.Write(value.m02); - writer.Write(value.m12); - writer.Write(value.m22); - writer.Write(value.m32); - writer.Write(value.m03); - writer.Write(value.m13); - writer.Write(value.m23); - writer.Write(value.m33); - } - - public global::UnityEngine.Matrix4x4 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __m00__ = default(float); - var __m10__ = default(float); - var __m20__ = default(float); - var __m30__ = default(float); - var __m01__ = default(float); - var __m11__ = default(float); - var __m21__ = default(float); - var __m31__ = default(float); - var __m02__ = default(float); - var __m12__ = default(float); - var __m22__ = default(float); - var __m32__ = default(float); - var __m03__ = default(float); - var __m13__ = default(float); - var __m23__ = default(float); - var __m33__ = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __m00__ = reader.ReadSingle(); - break; - case 1: - __m10__ = reader.ReadSingle(); - break; - case 2: - __m20__ = reader.ReadSingle(); - break; - case 3: - __m30__ = reader.ReadSingle(); - break; - case 4: - __m01__ = reader.ReadSingle(); - break; - case 5: - __m11__ = reader.ReadSingle(); - break; - case 6: - __m21__ = reader.ReadSingle(); - break; - case 7: - __m31__ = reader.ReadSingle(); - break; - case 8: - __m02__ = reader.ReadSingle(); - break; - case 9: - __m12__ = reader.ReadSingle(); - break; - case 10: - __m22__ = reader.ReadSingle(); - break; - case 11: - __m32__ = reader.ReadSingle(); - break; - case 12: - __m03__ = reader.ReadSingle(); - break; - case 13: - __m13__ = reader.ReadSingle(); - break; - case 14: - __m23__ = reader.ReadSingle(); - break; - case 15: - __m33__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = default(global::UnityEngine.Matrix4x4); - ____result.m00 = __m00__; - ____result.m10 = __m10__; - ____result.m20 = __m20__; - ____result.m30 = __m30__; - ____result.m01 = __m01__; - ____result.m11 = __m11__; - ____result.m21 = __m21__; - ____result.m31 = __m31__; - ____result.m02 = __m02__; - ____result.m12 = __m12__; - ____result.m22 = __m22__; - ____result.m32 = __m32__; - ____result.m03 = __m03__; - ____result.m13 = __m13__; - ____result.m23 = __m23__; - ____result.m33 = __m33__; - return ____result; - } - } - - public sealed class GradientColorKeyFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.GradientColorKey value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.color, options); - writer.Write(value.time); - } - - public global::UnityEngine.GradientColorKey Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __color__ = default(global::UnityEngine.Color); - var __time__ = default(float); - IFormatterResolver resolver = options.Resolver; - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __color__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __time__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.GradientColorKey(__color__, __time__); - ____result.color = __color__; - ____result.time = __time__; - return ____result; - } - } - - public sealed class GradientAlphaKeyFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.GradientAlphaKey value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.Write(value.alpha); - writer.Write(value.time); - } - - public global::UnityEngine.GradientAlphaKey Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __alpha__ = default(float); - var __time__ = default(float); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __alpha__ = reader.ReadSingle(); - break; - case 1: - __time__ = reader.ReadSingle(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.GradientAlphaKey(__alpha__, __time__); - ____result.alpha = __alpha__; - ____result.time = __time__; - return ____result; - } - } - - public sealed class GradientFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Gradient value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver resolver = options.Resolver; - writer.WriteArrayHeader(3); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.colorKeys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.alphaKeys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.mode, options); - } - - public global::UnityEngine.Gradient Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; - } - - IFormatterResolver resolver = options.Resolver; - var length = reader.ReadArrayHeader(); - var __colorKeys__ = default(global::UnityEngine.GradientColorKey[]); - var __alphaKeys__ = default(global::UnityEngine.GradientAlphaKey[]); - var __mode__ = default(global::UnityEngine.GradientMode); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __colorKeys__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __alphaKeys__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __mode__ = resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Gradient(); - ____result.colorKeys = __colorKeys__; - ____result.alphaKeys = __alphaKeys__; - ____result.mode = __mode__; - return ____result; - } - } - - public sealed class Color32Formatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Color32 value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.Write(value.r); - writer.Write(value.g); - writer.Write(value.b); - writer.Write(value.a); - } - - public global::UnityEngine.Color32 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __r__ = default(byte); - var __g__ = default(byte); - var __b__ = default(byte); - var __a__ = default(byte); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __r__ = reader.ReadByte(); - break; - case 1: - __g__ = reader.ReadByte(); - break; - case 2: - __b__ = reader.ReadByte(); - break; - case 3: - __a__ = reader.ReadByte(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Color32(__r__, __g__, __b__, __a__); - ____result.r = __r__; - ____result.g = __g__; - ____result.b = __b__; - ____result.a = __a__; - return ____result; - } - } - - public sealed class RectOffsetFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectOffset value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - writer.WriteArrayHeader(4); - writer.Write(value.left); - writer.Write(value.right); - writer.Write(value.top); - writer.Write(value.bottom); - } - - public global::UnityEngine.RectOffset Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - return null; - } - - var length = reader.ReadArrayHeader(); - var __left__ = default(int); - var __right__ = default(int); - var __top__ = default(int); - var __bottom__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __left__ = reader.ReadInt32(); - break; - case 1: - __right__ = reader.ReadInt32(); - break; - case 2: - __top__ = reader.ReadInt32(); - break; - case 3: - __bottom__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.RectOffset(); - ____result.left = __left__; - ____result.right = __right__; - ____result.top = __top__; - ____result.bottom = __bottom__; - return ____result; - } - } - - public sealed class LayerMaskFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.LayerMask value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(1); - writer.Write(value.value); - } - - public global::UnityEngine.LayerMask Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - - var length = reader.ReadArrayHeader(); - var __value__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __value__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = default(global::UnityEngine.LayerMask); - ____result.value = __value__; - return ____result; - } - } -#if UNITY_2017_2_OR_NEWER - public sealed class Vector2IntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector2Int value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.WriteInt32(value.x); - writer.WriteInt32(value.y); - } - public global::UnityEngine.Vector2Int Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __x__ = default(int); - var __y__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __x__ = reader.ReadInt32(); - break; - case 1: - __y__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Vector2Int(__x__, __y__); - ____result.x = __x__; - ____result.y = __y__; - return ____result; - } - } - - public sealed class Vector3IntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3Int value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(3); - writer.WriteInt32(value.x); - writer.WriteInt32(value.y); - writer.WriteInt32(value.z); - } - public global::UnityEngine.Vector3Int Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __x__ = default(int); - var __y__ = default(int); - var __z__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __x__ = reader.ReadInt32(); - break; - case 1: - __y__ = reader.ReadInt32(); - break; - case 2: - __z__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.Vector3Int(__x__, __y__, __z__); - ____result.x = __x__; - ____result.y = __y__; - ____result.z = __z__; - return ____result; - } - } - - public sealed class RangeIntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RangeInt value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - writer.WriteInt32(value.start); - writer.WriteInt32(value.length); - } - public global::UnityEngine.RangeInt Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __start__ = default(int); - var __length__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __start__ = reader.ReadInt32(); - break; - case 1: - __length__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.RangeInt(__start__, __length__); - ____result.start = __start__; - ____result.length = __length__; - return ____result; - } - } - - public sealed class RectIntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectInt value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(4); - writer.WriteInt32(value.x); - writer.WriteInt32(value.y); - writer.WriteInt32(value.width); - writer.WriteInt32(value.height); - } - public global::UnityEngine.RectInt Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __x__ = default(int); - var __y__ = default(int); - var __width__ = default(int); - var __height__ = default(int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __x__ = reader.ReadInt32(); - break; - case 1: - __y__ = reader.ReadInt32(); - break; - case 2: - __width__ = reader.ReadInt32(); - break; - case 3: - __height__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.RectInt(__x__, __y__, __width__, __height__); - ____result.x = __x__; - ____result.y = __y__; - ____result.width = __width__; - ____result.height = __height__; - return ____result; - } - } - - public sealed class BoundsIntFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.BoundsInt value, global::MessagePack.MessagePackSerializerOptions options) - { - writer.WriteArrayHeader(2); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.position, options); - options.Resolver.GetFormatterWithVerify().Serialize(ref writer, value.size, options); - } - public global::UnityEngine.BoundsInt Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.IsNil) - { - throw new InvalidOperationException("typecode is null, struct not supported"); - } - var length = reader.ReadArrayHeader(); - var __position__ = default(global::UnityEngine.Vector3Int); - var __size__ = default(global::UnityEngine.Vector3Int); - for (int i = 0; i < length; i++) - { - var key = i; - switch (key) - { - case 0: - __position__ = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 1: - __size__ = options.Resolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::UnityEngine.BoundsInt(__position__, __size__); - ____result.position = __position__; - ____result.size = __size__; - return ____result; - } - } -#endif -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Formatters.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Formatters.cs.meta deleted file mode 100644 index ffc5996..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/Formatters.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 43031b10b3132bf438ca856926d4a8f8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/MessagePackWindow.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/MessagePackWindow.cs deleted file mode 100644 index 013ad79..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/MessagePackWindow.cs +++ /dev/null @@ -1,314 +0,0 @@ -#if UNITY_EDITOR - -using System; -using System.Diagnostics; -using System.Text; -using System.Threading.Tasks; -using UnityEditor; -using UnityEngine; - -namespace MessagePack.Unity.Editor -{ - internal class MessagePackWindow : EditorWindow - { - static MessagePackWindow window; - - bool processInitialized; - - bool isDotnetInstalled; - string dotnetVersion; - - bool isInstalledMpc; - bool installingMpc; - bool invokingMpc; - - MpcArgument mpcArgument; - - [MenuItem("Window/MessagePack/CodeGenerator")] - public static void OpenWindow() - { - if (window != null) - { - window.Close(); - } - - // will called OnEnable(singleton instance will be set). - GetWindow("MessagePack CodeGen").Show(); - } - - async void OnEnable() - { - window = this; // set singleton. - try - { - var dotnet = await ProcessHelper.FindDotnetAsync(); - isDotnetInstalled = dotnet.found; - dotnetVersion = dotnet.version; - - if (isDotnetInstalled) - { - isInstalledMpc = await ProcessHelper.IsInstalledMpc(); - } - } - finally - { - mpcArgument = MpcArgument.Restore(); - processInitialized = true; - } - } - - async void OnGUI() - { - if (!processInitialized) - { - GUILayout.Label("Check .NET Core SDK/CodeGen install status."); - return; - } - if (mpcArgument == null) - { - return; - } - - if (!isDotnetInstalled) - { - GUILayout.Label(".NET Core SDK not found."); - GUILayout.Label("MessagePack CodeGen requires .NET Core Runtime."); - if (GUILayout.Button("Open .NET Core install page.")) - { - Application.OpenURL("https://dotnet.microsoft.com/download"); - } - return; - } - - if (!isInstalledMpc) - { - GUILayout.Label("MessagePack CodeGen does not instaled."); - EditorGUI.BeginDisabledGroup(installingMpc); - - if (GUILayout.Button("Install MessagePack CodeGen.")) - { - installingMpc = true; - try - { - var log = await ProcessHelper.InstallMpc(); - if (!string.IsNullOrWhiteSpace(log)) - { - UnityEngine.Debug.Log(log); - } - if (log != null && log.Contains("error")) - { - isInstalledMpc = false; - } - else - { - isInstalledMpc = true; - } - } - finally - { - installingMpc = false; - } - return; - } - - EditorGUI.EndDisabledGroup(); - return; - } - - EditorGUILayout.LabelField("-i input path(csproj or directory):"); - TextField(mpcArgument, x => x.Input, (x, y) => x.Input = y); - - EditorGUILayout.LabelField("-o output filepath(.cs) or directory(multiple):"); - TextField(mpcArgument, x => x.Output, (x, y) => x.Output = y); - - EditorGUILayout.LabelField("-m(optional) use map mode:"); - var newToggle = EditorGUILayout.Toggle(mpcArgument.UseMapMode); - if (mpcArgument.UseMapMode != newToggle) - { - mpcArgument.UseMapMode = newToggle; - mpcArgument.Save(); - } - - EditorGUILayout.LabelField("-c(optional) conditional compiler symbols(split with ','):"); - TextField(mpcArgument, x => x.ConditionalSymbol, (x, y) => x.ConditionalSymbol = y); - - EditorGUILayout.LabelField("-r(optional) generated resolver name:"); - TextField(mpcArgument, x => x.ResolverName, (x, y) => x.ResolverName = y); - - EditorGUILayout.LabelField("-n(optional) namespace root name:"); - TextField(mpcArgument, x => x.Namespace, (x, y) => x.Namespace = y); - - EditorGUILayout.LabelField("-ms(optional) Generate #if-- files by symbols, split with ','"); - TextField(mpcArgument, x => x.MultipleIfDirectiveOutputSymbols, (x, y) => x.MultipleIfDirectiveOutputSymbols = y); - - EditorGUI.BeginDisabledGroup(invokingMpc); - if (GUILayout.Button("Generate")) - { - var commnadLineArguments = mpcArgument.ToString(); - UnityEngine.Debug.Log("Generate MessagePack Files, command:" + commnadLineArguments); - - invokingMpc = true; - try - { - var log = await ProcessHelper.InvokeProcessStartAsync("mpc", commnadLineArguments); - UnityEngine.Debug.Log(log); - } - finally - { - invokingMpc = false; - } - } - EditorGUI.EndDisabledGroup(); - } - - void TextField(MpcArgument args, Func getter, Action setter) - { - var current = getter(args); - var newValue = EditorGUILayout.TextField(current); - if (newValue != current) - { - setter(args, newValue); - args.Save(); - } - } - } - - internal class MpcArgument - { - public string Input; - public string Output; - public string ConditionalSymbol; - public string ResolverName; - public string Namespace; - public bool UseMapMode; - public string MultipleIfDirectiveOutputSymbols; - - static string Key => "MessagePackCodeGen." + Application.productName; - - public static MpcArgument Restore() - { - if (EditorPrefs.HasKey(Key)) - { - var json = EditorPrefs.GetString(Key); - return JsonUtility.FromJson(json); - } - else - { - return new MpcArgument(); - } - } - - public void Save() - { - var json = JsonUtility.ToJson(this); - EditorPrefs.SetString(Key, json); - } - - public override string ToString() - { - var sb = new StringBuilder(); - sb.Append("-i "); sb.Append(Input); - sb.Append(" -o "); sb.Append(Output); - if (!string.IsNullOrWhiteSpace(ConditionalSymbol)) - { - sb.Append(" -c "); sb.Append(ConditionalSymbol); - } - if (!string.IsNullOrWhiteSpace(ResolverName)) - { - sb.Append(" -r "); sb.Append(ResolverName); - } - if (UseMapMode) - { - sb.Append(" -m"); - } - if (!string.IsNullOrWhiteSpace(Namespace)) - { - sb.Append(" -n "); sb.Append(Namespace); - } - if (!string.IsNullOrWhiteSpace(MultipleIfDirectiveOutputSymbols)) - { - sb.Append(" -ms "); sb.Append(MultipleIfDirectiveOutputSymbols); - } - - return sb.ToString(); - } - } - - internal static class ProcessHelper - { - const string InstallName = "messagepack.generator"; - - public static async Task IsInstalledMpc() - { - var list = await InvokeProcessStartAsync("dotnet", "tool list -g"); - if (list.Contains(InstallName)) - { - return true; - } - else - { - return false; - } - } - - public static async Task InstallMpc() - { - return await InvokeProcessStartAsync("dotnet", "tool install --global " + InstallName); - } - - public static async Task<(bool found, string version)> FindDotnetAsync() - { - try - { - var version = await InvokeProcessStartAsync("dotnet", "--version"); - return (true, version); - } - catch - { - return (false, null); - } - } - - public static Task InvokeProcessStartAsync(string fileName, string arguments) - { - var psi = new ProcessStartInfo() - { - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - StandardOutputEncoding = Encoding.UTF8, - StandardErrorEncoding = Encoding.UTF8, - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - FileName = fileName, - Arguments = arguments, - WorkingDirectory = Application.dataPath - }; - - Process p; - try - { - p = Process.Start(psi); - } - catch (Exception ex) - { - return Task.FromException(ex); - } - - var tcs = new TaskCompletionSource(); - p.EnableRaisingEvents = true; - p.Exited += (object sender, System.EventArgs e) => - { - var data = p.StandardOutput.ReadToEnd(); - p.Dispose(); - p = null; - - tcs.TrySetResult(data); - }; - - return tcs.Task; - } - } -} - -#endif diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/MessagePackWindow.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/MessagePackWindow.cs.meta deleted file mode 100644 index 1b1eb68..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/MessagePackWindow.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c7b2124e98ab01345a59ac40b0979625 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/UnityResolver.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/UnityResolver.cs deleted file mode 100644 index 033e513..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/UnityResolver.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using MessagePack.Formatters; -using UnityEngine; - -namespace MessagePack.Unity -{ - public class UnityResolver : IFormatterResolver - { - public static readonly UnityResolver Instance = new UnityResolver(); - - private UnityResolver() - { - } - - public IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - public static readonly IMessagePackFormatter Formatter; - - static FormatterCache() - { - Formatter = (IMessagePackFormatter)UnityResolveryResolverGetFormatterHelper.GetFormatter(typeof(T)); - } - } - } - - internal static class UnityResolveryResolverGetFormatterHelper - { - private static readonly Dictionary FormatterMap = new Dictionary() - { - // standard - { typeof(Vector2), new Vector2Formatter() }, - { typeof(Vector3), new Vector3Formatter() }, - { typeof(Vector4), new Vector4Formatter() }, - { typeof(Quaternion), new QuaternionFormatter() }, - { typeof(Color), new ColorFormatter() }, - { typeof(Bounds), new BoundsFormatter() }, - { typeof(Rect), new RectFormatter() }, - { typeof(Vector2?), new StaticNullableFormatter(new Vector2Formatter()) }, - { typeof(Vector3?), new StaticNullableFormatter(new Vector3Formatter()) }, - { typeof(Vector4?), new StaticNullableFormatter(new Vector4Formatter()) }, - { typeof(Quaternion?), new StaticNullableFormatter(new QuaternionFormatter()) }, - { typeof(Color?), new StaticNullableFormatter(new ColorFormatter()) }, - { typeof(Bounds?), new StaticNullableFormatter(new BoundsFormatter()) }, - { typeof(Rect?), new StaticNullableFormatter(new RectFormatter()) }, - - // standard + array - { typeof(Vector2[]), new ArrayFormatter() }, - { typeof(Vector3[]), new ArrayFormatter() }, - { typeof(Vector4[]), new ArrayFormatter() }, - { typeof(Quaternion[]), new ArrayFormatter() }, - { typeof(Color[]), new ArrayFormatter() }, - { typeof(Bounds[]), new ArrayFormatter() }, - { typeof(Rect[]), new ArrayFormatter() }, - { typeof(Vector2?[]), new ArrayFormatter() }, - { typeof(Vector3?[]), new ArrayFormatter() }, - { typeof(Vector4?[]), new ArrayFormatter() }, - { typeof(Quaternion?[]), new ArrayFormatter() }, - { typeof(Color?[]), new ArrayFormatter() }, - { typeof(Bounds?[]), new ArrayFormatter() }, - { typeof(Rect?[]), new ArrayFormatter() }, - - // standard + list - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - - // new - { typeof(AnimationCurve), new AnimationCurveFormatter() }, - { typeof(RectOffset), new RectOffsetFormatter() }, - { typeof(Gradient), new GradientFormatter() }, - { typeof(WrapMode), new WrapModeFormatter() }, - { typeof(GradientMode), new GradientModeFormatter() }, - { typeof(Keyframe), new KeyframeFormatter() }, - { typeof(Matrix4x4), new Matrix4x4Formatter() }, - { typeof(GradientColorKey), new GradientColorKeyFormatter() }, - { typeof(GradientAlphaKey), new GradientAlphaKeyFormatter() }, - { typeof(Color32), new Color32Formatter() }, - { typeof(LayerMask), new LayerMaskFormatter() }, - { typeof(WrapMode?), new StaticNullableFormatter(new WrapModeFormatter()) }, - { typeof(GradientMode?), new StaticNullableFormatter(new GradientModeFormatter()) }, - { typeof(Keyframe?), new StaticNullableFormatter(new KeyframeFormatter()) }, - { typeof(Matrix4x4?), new StaticNullableFormatter(new Matrix4x4Formatter()) }, - { typeof(GradientColorKey?), new StaticNullableFormatter(new GradientColorKeyFormatter()) }, - { typeof(GradientAlphaKey?), new StaticNullableFormatter(new GradientAlphaKeyFormatter()) }, - { typeof(Color32?), new StaticNullableFormatter(new Color32Formatter()) }, - { typeof(LayerMask?), new StaticNullableFormatter(new LayerMaskFormatter()) }, - - // new + array - { typeof(AnimationCurve[]), new ArrayFormatter() }, - { typeof(RectOffset[]), new ArrayFormatter() }, - { typeof(Gradient[]), new ArrayFormatter() }, - { typeof(WrapMode[]), new ArrayFormatter() }, - { typeof(GradientMode[]), new ArrayFormatter() }, - { typeof(Keyframe[]), new ArrayFormatter() }, - { typeof(Matrix4x4[]), new ArrayFormatter() }, - { typeof(GradientColorKey[]), new ArrayFormatter() }, - { typeof(GradientAlphaKey[]), new ArrayFormatter() }, - { typeof(Color32[]), new ArrayFormatter() }, - { typeof(LayerMask[]), new ArrayFormatter() }, - { typeof(WrapMode?[]), new ArrayFormatter() }, - { typeof(GradientMode?[]), new ArrayFormatter() }, - { typeof(Keyframe?[]), new ArrayFormatter() }, - { typeof(Matrix4x4?[]), new ArrayFormatter() }, - { typeof(GradientColorKey?[]), new ArrayFormatter() }, - { typeof(GradientAlphaKey?[]), new ArrayFormatter() }, - { typeof(Color32?[]), new ArrayFormatter() }, - { typeof(LayerMask?[]), new ArrayFormatter() }, - - // new + list - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - { typeof(List), new ListFormatter() }, - - // unity 2017.2 -#if UNITY_2017_2_OR_NEWER - - {typeof(Vector2Int), new Vector2IntFormatter()}, - {typeof(Vector3Int), new Vector3IntFormatter()}, - {typeof(RangeInt), new RangeIntFormatter()}, - {typeof(RectInt), new RectIntFormatter()}, - {typeof(BoundsInt), new BoundsIntFormatter()}, - {typeof(Vector2Int?), new StaticNullableFormatter(new Vector2IntFormatter())}, - {typeof(Vector3Int?), new StaticNullableFormatter(new Vector3IntFormatter())}, - {typeof(RangeInt?), new StaticNullableFormatter(new RangeIntFormatter())}, - {typeof(RectInt?), new StaticNullableFormatter(new RectIntFormatter())}, - {typeof(BoundsInt?), new StaticNullableFormatter(new BoundsIntFormatter())}, - // unity 2017.2 + array - {typeof(Vector2Int[]), new ArrayFormatter()}, - {typeof(Vector3Int[]), new ArrayFormatter()}, - {typeof(RangeInt[]), new ArrayFormatter()}, - {typeof(RectInt[]), new ArrayFormatter()}, - {typeof(BoundsInt[]), new ArrayFormatter()}, - {typeof(Vector2Int?[]), new ArrayFormatter()}, - {typeof(Vector3Int?[]), new ArrayFormatter()}, - {typeof(RangeInt?[]), new ArrayFormatter()}, - {typeof(RectInt?[]), new ArrayFormatter()}, - {typeof(BoundsInt?[]), new ArrayFormatter()}, - // unity 2017.2 + list - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - {typeof(List), new ListFormatter()}, - -#endif - }; - - internal static object GetFormatter(Type t) - { - object formatter; - if (FormatterMap.TryGetValue(t, out formatter)) - { - return formatter; - } - - return null; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/UnityResolver.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/UnityResolver.cs.meta deleted file mode 100644 index 148f5be..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Unity/UnityResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 88a64133a719d3e40a7725f13b2f0191 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Utilities.cs b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Utilities.cs deleted file mode 100644 index 8d5a4cf..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Utilities.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Buffers; - -namespace MessagePack -{ - /// - /// Internal utilities and extension methods for various external types. - /// - internal static class Utilities - { - /// - /// A value indicating whether we're running on mono. - /// -#if UNITY_2018_3_OR_NEWER - internal const bool IsMono = true; // hard code since we haven't tested whether mono is detected on all unity platforms. -#else - internal static readonly bool IsMono = Type.GetType("Mono.Runtime") is Type; -#endif - - internal delegate void GetWriterBytesAction(ref MessagePackWriter writer, TArg argument); - - internal static byte[] GetWriterBytes(TArg arg, GetWriterBytesAction action) - { - using (var sequenceRental = SequencePool.Shared.Rent()) - { - var writer = new MessagePackWriter(sequenceRental.Value); - action(ref writer, arg); - writer.Flush(); - return sequenceRental.Value.AsReadOnlySequence.ToArray(); - } - } - - internal static Memory GetMemoryCheckResult(this IBufferWriter bufferWriter, int size = 0) - { - var memory = bufferWriter.GetMemory(size); - if (memory.IsEmpty) - { - throw new InvalidOperationException("The underlying IBufferWriter.GetMemory(int) method returned an empty memory block, which is not allowed. This is a bug in " + bufferWriter.GetType().FullName); - } - - return memory; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Utilities.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Utilities.cs.meta deleted file mode 100644 index 9a25295..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/Utilities.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f968cf11be4a47f42a5b1fcb33a6bf6b -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/package.json b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/package.json deleted file mode 100644 index 369e377..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "com.neuecc.messagepack", - "displayName": "MessagePack", - "version": "2.2.60", - "unity": "2018.4", - "description": "Extremely Fast MessagePack Serializer for C#.", - "keywords": [ "Serializer" ], - "license": "MIT", - "category": "Scripting", - "dependencies": {} -} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/package.json.meta b/src/MasterMemory.Unity/Assets/Scripts/MessagePack/package.json.meta deleted file mode 100644 index 51ea8bd..0000000 --- a/src/MasterMemory.Unity/Assets/Scripts/MessagePack/package.json.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 3b8639f4c743fac45bc51854f278b3b1 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Scripts/NewBehaviourScript.cs b/src/MasterMemory.Unity/Assets/Scripts/NewBehaviourScript.cs new file mode 100644 index 0000000..7113df9 --- /dev/null +++ b/src/MasterMemory.Unity/Assets/Scripts/NewBehaviourScript.cs @@ -0,0 +1,76 @@ +using MasterMemory; +using MessagePack; +using MessagePack.Resolvers; +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using MyProj; + +[assembly: MasterMemoryGeneratorOptions(Namespace = "MyProj")] + +// If you want to use init, copy-and-paste this. +namespace System.Runtime.CompilerServices +{ + internal sealed class IsExternalInit { } +} + + + +public class NewBehaviourScript : MonoBehaviour +{ + // Start is called before the first frame update + void Start() + { + + } + + // Update is called once per frame + void Update() + { + + } +} + +public enum Gender +{ + Male, Female, Unknown +} + +// table definition marked by MemoryTableAttribute. +// database-table must be serializable by MessagePack-CSsharp +[MemoryTable("person"), MessagePackObject(true)] +public record Person +{ + // index definition by attributes. + [PrimaryKey] + public int PersonId { get; init; } + + // secondary index can add multiple(discriminated by index-number). + [SecondaryKey(0), NonUnique] + [SecondaryKey(1, keyOrder: 1), NonUnique] + public int Age { get; init; } + + [SecondaryKey(2), NonUnique] + [SecondaryKey(1, keyOrder: 0), NonUnique] + public Gender Gender { get; init; } + + public string Name { get; init; } +} + +public static class Initializer +{ + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void SetupMessagePackResolver() + { + // Create CompositeResolver + StaticCompositeResolver.Instance.Register(new[]{ + MasterMemoryResolver.Instance, // set MasterMemory generated resolver + StandardResolver.Instance // set default MessagePack resolver + }); + + // Set as default + var options = MessagePackSerializerOptions.Standard.WithResolver(StaticCompositeResolver.Instance); + MessagePackSerializer.DefaultOptions = options; + } +} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations/Attributes.cs.meta b/src/MasterMemory.Unity/Assets/Scripts/NewBehaviourScript.cs.meta similarity index 83% rename from src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations/Attributes.cs.meta rename to src/MasterMemory.Unity/Assets/Scripts/NewBehaviourScript.cs.meta index 96cd956..b083b17 100644 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/Annotations/Attributes.cs.meta +++ b/src/MasterMemory.Unity/Assets/Scripts/NewBehaviourScript.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b40c51820b55c0f4296a1878957d5bf5 +guid: a7e2d905f1c43ee42914ee6de131c41e MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/src/MasterMemory.Unity/Assets/Tests.meta b/src/MasterMemory.Unity/Assets/Tests.meta deleted file mode 100644 index 812fda9..0000000 --- a/src/MasterMemory.Unity/Assets/Tests.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 045b54ace96b9764bae81f0adca442d0 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/BinarySearchTest.cs b/src/MasterMemory.Unity/Assets/Tests/BinarySearchTest.cs deleted file mode 100644 index 05a6a5a..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/BinarySearchTest.cs +++ /dev/null @@ -1,107 +0,0 @@ -using MasterMemory.Internal; -using MessagePack.Resolvers; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using FluentAssertions; -using Xunit; -using MessagePack; - -namespace MasterMemory.Tests -{ - public class BinarySearchTest - { - public BinarySearchTest() - { - MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(MessagePackResolver.Instance); - } - - [Fact] - public void Find() - { - var rand = new Random(); - for (int iii = 0; iii < 30; iii++) - { - var seed = Enumerable.Range(1, 10); - var randomSeed = seed.Where(x => rand.Next() % 2 == 0); - - var array = randomSeed.Concat(randomSeed).Concat(randomSeed).Concat(randomSeed) - .OrderBy(x => x) - .ToArray(); - - for (int i = 1; i <= 10; i++) - { - var firstIndex = Array.IndexOf(array, i); - var lastIndex = Array.LastIndexOf(array, i); - - var f = BinarySearch.FindFirst(array, i, x => x, Comparer.Default); - var l = BinarySearch.LowerBound(array, 0, array.Length, i, x => x, Comparer.Default); - var u = BinarySearch.UpperBound(array, 0, array.Length, i, x => x, Comparer.Default); - - // not found - if (firstIndex == -1) - { - f.Should().Be(-1); - l.Should().Be(-1); - u.Should().Be(-1); - continue; - } - - array[f].Should().Be(i); - array[l].Should().Be(i); - array[u].Should().Be(i); - - l.Should().Be(firstIndex); - u.Should().Be(lastIndex); - } - } - - // and empty - var emptyArray = Enumerable.Empty().ToArray(); - BinarySearch.FindFirst(emptyArray, 0, x => x, Comparer.Default).Should().Be(-1); - BinarySearch.LowerBound(emptyArray, 0, emptyArray.Length, 0, x => x, Comparer.Default).Should().Be(-1); - BinarySearch.UpperBound(emptyArray, 0, emptyArray.Length, 0, x => x, Comparer.Default).Should().Be(-1); - } - - [Fact] - public void Closest() - { - // empty - var array = Enumerable.Empty().ToArray(); - - var near = BinarySearch.FindClosest(array, 0, 0, array.Length, x => x, Comparer.Default, false); - near.Should().Be(-1); - - // mid - var source = new[]{ - new { id = 0, bound = 0 }, - new { id = 1, bound = 100 }, - new { id = 2, bound = 200 }, - new { id = 3, bound = 300 }, - new { id = 4, bound = 500 }, - new { id = 5, bound = 1000 }, - }; - - BinarySearch.FindClosest(source, 0, source.Length, -100, x => x.bound, Comparer.Default, true).Should().Be(-1); -// BinarySearch.FindClosest(source, 0, source.Length, -100, x => x.bound, Comparer.Default, true).Should().Be(0); - BinarySearch.FindClosest(source, 0, source.Length, 0, x => x.bound, Comparer.Default, true).Should().Be(0); - BinarySearch.FindClosest(source, 0, source.Length, 10, x => x.bound, Comparer.Default, true).Should().Be(0); - BinarySearch.FindClosest(source, 0, source.Length, 50, x => x.bound, Comparer.Default, true).Should().Be(0); - - source[BinarySearch.FindClosest(source, 0, source.Length, 100, x => x.bound, Comparer.Default, true)].id.Should().Be(1); - source[BinarySearch.FindClosest(source, 0, source.Length, 100, x => x.bound, Comparer.Default, false)].id.Should().Be(1); - - source[BinarySearch.FindClosest(source, 0, source.Length, 150, x => x.bound, Comparer.Default, true)].id.Should().Be(1); - source[BinarySearch.FindClosest(source, 0, source.Length, 300, x => x.bound, Comparer.Default, true)].id.Should().Be(3); - source[BinarySearch.FindClosest(source, 0, source.Length, 999, x => x.bound, Comparer.Default, true)].id.Should().Be(4); - source[BinarySearch.FindClosest(source, 0, source.Length, 1000, x => x.bound, Comparer.Default, true)].id.Should().Be(5); - source[BinarySearch.FindClosest(source, 0, source.Length, 1001, x => x.bound, Comparer.Default, true)].id.Should().Be(5); - source[BinarySearch.FindClosest(source, 0, source.Length, 10000, x => x.bound, Comparer.Default, true)].id.Should().Be(5); -// source[BinarySearch.FindClosest(source, 0, source.Length, 10000, x => x.bound, Comparer.Default, false)].id.Should().Be(5); - - BinarySearch.FindClosest(source, 0, source.Length, 10000, x => x.bound, Comparer.Default, false).Should().Be(6); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/BinarySearchTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/BinarySearchTest.cs.meta deleted file mode 100644 index cdd4634..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/BinarySearchTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 575e18f43079ac745bfedabe3782c458 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/DatabaseTest.cs b/src/MasterMemory.Unity/Assets/Tests/DatabaseTest.cs deleted file mode 100644 index 6ae0ce6..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/DatabaseTest.cs +++ /dev/null @@ -1,127 +0,0 @@ -using FluentAssertions; -using MessagePack; -using MessagePack.Resolvers; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Xunit; - -namespace MasterMemory.Tests -{ - public class DatabaseTest - { - public DatabaseTest() - { - MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(MessagePackResolver.Instance); - } - - Sample[] CreateData() - { - // Id = Unique, PK - // FirstName + LastName = Unique - var data = new[] - { - new Sample { Id = 5, Age = 19, FirstName = "aaa", LastName = "foo" }, - new Sample { Id = 6, Age = 29, FirstName = "bbb", LastName = "foo" }, - new Sample { Id = 7, Age = 39, FirstName = "ccc", LastName = "foo" }, - new Sample { Id = 8, Age = 49, FirstName = "ddd", LastName = "foo" }, - new Sample { Id = 1, Age = 59, FirstName = "eee", LastName = "foo" }, - new Sample { Id = 2, Age = 89, FirstName = "aaa", LastName = "bar" }, - new Sample { Id = 3, Age = 79, FirstName = "be", LastName = "de" }, - new Sample { Id = 4, Age = 89, FirstName = "aaa", LastName = "tako" }, - new Sample { Id = 9, Age = 99, FirstName = "aaa", LastName = "ika" }, - new Sample { Id = 10, Age = 9, FirstName = "eee", LastName = "baz" }, - }; - return data; - } - - [Fact] - public void SingleDb() - { - var builder = new DatabaseBuilder(); - builder.Append(CreateData()); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - db.SampleTable.FindById(8).Age.Should().Be(49); - - var tableInfo = MemoryDatabase.GetTableInfo(bin); - tableInfo[0].TableName.Should().Be("s_a_m_p_l_e"); - } - - [Fact] - public void All() - { - var builder = new DatabaseBuilder(); - builder.Append(CreateData()); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - - db.SampleTable.All.Select(x => x.Id).ToArray().Should().BeEquivalentTo(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - db.SampleTable.AllReverse.Select(x => x.Id).ToArray().Should().BeEquivalentTo(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }.Reverse()); - db.SampleTable.SortByAge.Select(x => x.Id).OrderBy(x => x).ToArray().Should().BeEquivalentTo(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - } - - [Fact] - public void Ranges() - { - var builder = new DatabaseBuilder(); - builder.Append(CreateData()); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - - db.SampleTable.FindRangeByAge(2,2).Select(x=>x.Id).ToArray().Should().BeEquivalentTo( new int[] {} ); - db.SampleTable.FindRangeByAge(30,50).Select(x=>x.Id).ToArray().Should().BeEquivalentTo( new int[] { 7, 8 } ); - db.SampleTable.FindRangeByAge(100,100).Select(x=>x.Id).ToArray().Should().BeEquivalentTo( new int[] {} ); - } - - - [Fact] - public void EmptyAll() - { - { - var builder = new DatabaseBuilder(); - builder.Append(new Sample[] { }); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - - db.SampleTable.All.Any().Should().BeFalse(); - } - { - var builder = new DatabaseBuilder(); - builder.Append(new Sample[] { }.Select(x => x)); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - - db.SampleTable.All.Any().Should().BeFalse(); - } - } - - [Fact] - public void WithNull() - { - var builder = new DatabaseBuilder(); - builder.Append(new Sample[] {new Sample - { - Age = 10, - FirstName = null, - Id = 999, - LastName = "abcde" - } }); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - - var sample = db.SampleTable.FindById(999); - sample.Age.Should().Be(10); - sample.FirstName.Should().BeNull(); - sample.LastName.Should().Be("abcde"); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/DatabaseTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/DatabaseTest.cs.meta deleted file mode 100644 index 15ea62d..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/DatabaseTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9a88850e5546c044eb85e42427d4a1d7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated.meta b/src/MasterMemory.Unity/Assets/Tests/Generated.meta deleted file mode 100644 index b04f797..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 4b7a48f8a8bdf5441835020eea99dfff -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/DatabaseBuilder.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/DatabaseBuilder.cs deleted file mode 100644 index b3664dd..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/DatabaseBuilder.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public sealed class DatabaseBuilder : DatabaseBuilderBase - { - public DatabaseBuilder() : this(null) { } - public DatabaseBuilder(MessagePack.IFormatterResolver resolver) : base(resolver) { } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.RandomId, System.StringComparer.Ordinal); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.QuestId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.ItemId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.QuestId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.ItemId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.TestID, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Level, System.Collections.Generic.Comparer.Default); - return this; - } - - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/DatabaseBuilder.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/DatabaseBuilder.cs.meta deleted file mode 100644 index ec1a949..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/DatabaseBuilder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 89503e668741f294e8eae4b37e8bd1a3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/ImmutableBuilder.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/ImmutableBuilder.cs deleted file mode 100644 index 3468646..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/ImmutableBuilder.cs +++ /dev/null @@ -1,766 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public sealed class ImmutableBuilder : ImmutableBuilderBase - { - MemoryDatabase memory; - - public ImmutableBuilder(MemoryDatabase memory) - { - this.memory = memory; - } - - public MemoryDatabase Build() - { - return memory; - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.RandomId, System.StringComparer.Ordinal); - var table = new PersonModelTable(newData); - memory = new MemoryDatabase( - table, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemovePersonModel(string[] keys) - { - var data = RemoveCore(memory.PersonModelTable.GetRawDataUnsafe(), keys, x => x.RandomId, System.StringComparer.Ordinal); - var newData = CloneAndSortBy(data, x => x.RandomId, System.StringComparer.Ordinal); - var table = new PersonModelTable(newData); - memory = new MemoryDatabase( - table, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(PersonModel[] addOrReplaceData) - { - var data = DiffCore(memory.PersonModelTable.GetRawDataUnsafe(), addOrReplaceData, x => x.RandomId, System.StringComparer.Ordinal); - var newData = CloneAndSortBy(data, x => x.RandomId, System.StringComparer.Ordinal); - var table = new PersonModelTable(newData); - memory = new MemoryDatabase( - table, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - table, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveQuestMaster(int[] keys) - { - var data = RemoveCore(memory.QuestMasterTable.GetRawDataUnsafe(), keys, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - table, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(QuestMaster[] addOrReplaceData) - { - var data = DiffCore(memory.QuestMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - table, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - table, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveItemMaster(int[] keys) - { - var data = RemoveCore(memory.ItemMasterTable.GetRawDataUnsafe(), keys, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - table, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(ItemMaster[] addOrReplaceData) - { - var data = DiffCore(memory.ItemMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - table, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - table, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveQuestMasterEmptyValidate(int[] keys) - { - var data = RemoveCore(memory.QuestMasterEmptyValidateTable.GetRawDataUnsafe(), keys, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - table, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(QuestMasterEmptyValidate[] addOrReplaceData) - { - var data = DiffCore(memory.QuestMasterEmptyValidateTable.GetRawDataUnsafe(), addOrReplaceData, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - table, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - table, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveItemMasterEmptyValidate(int[] keys) - { - var data = RemoveCore(memory.ItemMasterEmptyValidateTable.GetRawDataUnsafe(), keys, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - table, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(ItemMasterEmptyValidate[] addOrReplaceData) - { - var data = DiffCore(memory.ItemMasterEmptyValidateTable.GetRawDataUnsafe(), addOrReplaceData, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - table, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SequentialCheckMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - table, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSequentialCheckMaster(int[] keys) - { - var data = RemoveCore(memory.SequentialCheckMasterTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SequentialCheckMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - table, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(SequentialCheckMaster[] addOrReplaceData) - { - var data = DiffCore(memory.SequentialCheckMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SequentialCheckMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - table, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SingleMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - table, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSingleMaster(int[] keys) - { - var data = RemoveCore(memory.SingleMasterTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SingleMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - table, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(SingleMaster[] addOrReplaceData) - { - var data = DiffCore(memory.SingleMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SingleMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - table, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new FailTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - table, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveFail(int[] keys) - { - var data = RemoveCore(memory.FailTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new FailTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - table, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(Fail[] addOrReplaceData) - { - var data = DiffCore(memory.FailTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new FailTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - table, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SampleTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - table, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSample(int[] keys) - { - var data = RemoveCore(memory.SampleTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SampleTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - table, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(Sample[] addOrReplaceData) - { - var data = DiffCore(memory.SampleTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SampleTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - table, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var table = new SkillMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - table, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSkillMaster((int SkillId, int SkillLevel)[] keys) - { - var data = RemoveCore(memory.SkillMasterTable.GetRawDataUnsafe(), keys, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var newData = CloneAndSortBy(data, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var table = new SkillMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - table, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(SkillMaster[] addOrReplaceData) - { - var data = DiffCore(memory.SkillMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var newData = CloneAndSortBy(data, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var table = new SkillMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - table, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.TestID, System.Collections.Generic.Comparer.Default); - var table = new TestMasterTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - table, - memory.UserLevelTable - - ); - } - - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Level, System.Collections.Generic.Comparer.Default); - var table = new UserLevelTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - table - - ); - } - - public void RemoveUserLevel(int[] keys) - { - var data = RemoveCore(memory.UserLevelTable.GetRawDataUnsafe(), keys, x => x.Level, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Level, System.Collections.Generic.Comparer.Default); - var table = new UserLevelTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - table - - ); - } - - public void Diff(UserLevel[] addOrReplaceData) - { - var data = DiffCore(memory.UserLevelTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Level, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Level, System.Collections.Generic.Comparer.Default); - var table = new UserLevelTable(newData); - memory = new MemoryDatabase( - memory.PersonModelTable, - memory.QuestMasterTable, - memory.ItemMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.ItemMasterEmptyValidateTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.FailTable, - memory.SampleTable, - memory.SkillMasterTable, - memory.TestMasterTable, - table - - ); - } - - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/ImmutableBuilder.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/ImmutableBuilder.cs.meta deleted file mode 100644 index 06fe6d4..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/ImmutableBuilder.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 52525a96351815247878ff351b7c7f84 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/MasterMemoryResolver.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/MasterMemoryResolver.cs deleted file mode 100644 index 7340a78..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/MasterMemoryResolver.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public class MasterMemoryResolver : global::MessagePack.IFormatterResolver - { - public static readonly global::MessagePack.IFormatterResolver Instance = new MasterMemoryResolver(); - - MasterMemoryResolver() - { - - } - - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() - { - return FormatterCache.formatter; - } - - static class FormatterCache - { - public static readonly global::MessagePack.Formatters.IMessagePackFormatter formatter; - - static FormatterCache() - { - var f = MasterMemoryResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (f != null) - { - formatter = (global::MessagePack.Formatters.IMessagePackFormatter)f; - } - } - } - } - - internal static class MasterMemoryResolverGetFormatterHelper - { - static readonly global::System.Collections.Generic.Dictionary lookup; - - static MasterMemoryResolverGetFormatterHelper() - { - lookup = new global::System.Collections.Generic.Dictionary(12) - { - {typeof(PersonModel[]), 0 }, - {typeof(QuestMaster[]), 1 }, - {typeof(ItemMaster[]), 2 }, - {typeof(QuestMasterEmptyValidate[]), 3 }, - {typeof(ItemMasterEmptyValidate[]), 4 }, - {typeof(SequentialCheckMaster[]), 5 }, - {typeof(SingleMaster[]), 6 }, - {typeof(Fail[]), 7 }, - {typeof(Sample[]), 8 }, - {typeof(SkillMaster[]), 9 }, - {typeof(TestMaster[]), 10 }, - {typeof(UserLevel[]), 11 }, - }; - } - - internal static object GetFormatter(Type t) - { - int key; - if (!lookup.TryGetValue(t, out key)) return null; - - switch (key) - { - case 0: return new MessagePack.Formatters.ArrayFormatter(); - case 1: return new MessagePack.Formatters.ArrayFormatter(); - case 2: return new MessagePack.Formatters.ArrayFormatter(); - case 3: return new MessagePack.Formatters.ArrayFormatter(); - case 4: return new MessagePack.Formatters.ArrayFormatter(); - case 5: return new MessagePack.Formatters.ArrayFormatter(); - case 6: return new MessagePack.Formatters.ArrayFormatter(); - case 7: return new MessagePack.Formatters.ArrayFormatter(); - case 8: return new MessagePack.Formatters.ArrayFormatter(); - case 9: return new MessagePack.Formatters.ArrayFormatter(); - case 10: return new MessagePack.Formatters.ArrayFormatter(); - case 11: return new MessagePack.Formatters.ArrayFormatter(); - default: return null; - } - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/MasterMemoryResolver.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/MasterMemoryResolver.cs.meta deleted file mode 100644 index 3a51593..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/MasterMemoryResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0443834c9890f9c40a67d4b1be490eac -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/MemoryDatabase.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/MemoryDatabase.cs deleted file mode 100644 index 290fc30..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/MemoryDatabase.cs +++ /dev/null @@ -1,207 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public sealed class MemoryDatabase : MemoryDatabaseBase - { - public PersonModelTable PersonModelTable { get; private set; } - public QuestMasterTable QuestMasterTable { get; private set; } - public ItemMasterTable ItemMasterTable { get; private set; } - public QuestMasterEmptyValidateTable QuestMasterEmptyValidateTable { get; private set; } - public ItemMasterEmptyValidateTable ItemMasterEmptyValidateTable { get; private set; } - public SequentialCheckMasterTable SequentialCheckMasterTable { get; private set; } - public SingleMasterTable SingleMasterTable { get; private set; } - public FailTable FailTable { get; private set; } - public SampleTable SampleTable { get; private set; } - public SkillMasterTable SkillMasterTable { get; private set; } - public TestMasterTable TestMasterTable { get; private set; } - public UserLevelTable UserLevelTable { get; private set; } - - public MemoryDatabase( - PersonModelTable PersonModelTable, - QuestMasterTable QuestMasterTable, - ItemMasterTable ItemMasterTable, - QuestMasterEmptyValidateTable QuestMasterEmptyValidateTable, - ItemMasterEmptyValidateTable ItemMasterEmptyValidateTable, - SequentialCheckMasterTable SequentialCheckMasterTable, - SingleMasterTable SingleMasterTable, - FailTable FailTable, - SampleTable SampleTable, - SkillMasterTable SkillMasterTable, - TestMasterTable TestMasterTable, - UserLevelTable UserLevelTable - ) - { - this.PersonModelTable = PersonModelTable; - this.QuestMasterTable = QuestMasterTable; - this.ItemMasterTable = ItemMasterTable; - this.QuestMasterEmptyValidateTable = QuestMasterEmptyValidateTable; - this.ItemMasterEmptyValidateTable = ItemMasterEmptyValidateTable; - this.SequentialCheckMasterTable = SequentialCheckMasterTable; - this.SingleMasterTable = SingleMasterTable; - this.FailTable = FailTable; - this.SampleTable = SampleTable; - this.SkillMasterTable = SkillMasterTable; - this.TestMasterTable = TestMasterTable; - this.UserLevelTable = UserLevelTable; - } - - public MemoryDatabase(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) - : base(databaseBinary, internString, formatterResolver, maxDegreeOfParallelism) - { - } - - protected override void Init(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - this.PersonModelTable = ExtractTableData(header, databaseBinary, options, xs => new PersonModelTable(xs)); - this.QuestMasterTable = ExtractTableData(header, databaseBinary, options, xs => new QuestMasterTable(xs)); - this.ItemMasterTable = ExtractTableData(header, databaseBinary, options, xs => new ItemMasterTable(xs)); - this.QuestMasterEmptyValidateTable = ExtractTableData(header, databaseBinary, options, xs => new QuestMasterEmptyValidateTable(xs)); - this.ItemMasterEmptyValidateTable = ExtractTableData(header, databaseBinary, options, xs => new ItemMasterEmptyValidateTable(xs)); - this.SequentialCheckMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SequentialCheckMasterTable(xs)); - this.SingleMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SingleMasterTable(xs)); - this.FailTable = ExtractTableData(header, databaseBinary, options, xs => new FailTable(xs)); - this.SampleTable = ExtractTableData(header, databaseBinary, options, xs => new SampleTable(xs)); - this.SkillMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SkillMasterTable(xs)); - this.TestMasterTable = ExtractTableData(header, databaseBinary, options, xs => new TestMasterTable(xs)); - this.UserLevelTable = ExtractTableData(header, databaseBinary, options, xs => new UserLevelTable(xs)); - } - - public ImmutableBuilder ToImmutableBuilder() - { - return new ImmutableBuilder(this); - } - - public DatabaseBuilder ToDatabaseBuilder() - { - var builder = new DatabaseBuilder(); - builder.Append(this.PersonModelTable.GetRawDataUnsafe()); - builder.Append(this.QuestMasterTable.GetRawDataUnsafe()); - builder.Append(this.ItemMasterTable.GetRawDataUnsafe()); - builder.Append(this.QuestMasterEmptyValidateTable.GetRawDataUnsafe()); - builder.Append(this.ItemMasterEmptyValidateTable.GetRawDataUnsafe()); - builder.Append(this.SequentialCheckMasterTable.GetRawDataUnsafe()); - builder.Append(this.SingleMasterTable.GetRawDataUnsafe()); - builder.Append(this.FailTable.GetRawDataUnsafe()); - builder.Append(this.SampleTable.GetRawDataUnsafe()); - builder.Append(this.SkillMasterTable.GetRawDataUnsafe()); - builder.Append(this.TestMasterTable.GetRawDataUnsafe()); - builder.Append(this.UserLevelTable.GetRawDataUnsafe()); - return builder; - } - - public ValidateResult Validate() - { - var result = new ValidateResult(); - var database = new ValidationDatabase(new object[] - { - PersonModelTable, - QuestMasterTable, - ItemMasterTable, - QuestMasterEmptyValidateTable, - ItemMasterEmptyValidateTable, - SequentialCheckMasterTable, - SingleMasterTable, - FailTable, - SampleTable, - SkillMasterTable, - TestMasterTable, - UserLevelTable, - }); - - ((ITableUniqueValidate)PersonModelTable).ValidateUnique(result); - ValidateTable(PersonModelTable.All, database, "RandomId", PersonModelTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)QuestMasterTable).ValidateUnique(result); - ValidateTable(QuestMasterTable.All, database, "QuestId", QuestMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)ItemMasterTable).ValidateUnique(result); - ValidateTable(ItemMasterTable.All, database, "ItemId", ItemMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)QuestMasterEmptyValidateTable).ValidateUnique(result); - ValidateTable(QuestMasterEmptyValidateTable.All, database, "QuestId", QuestMasterEmptyValidateTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)ItemMasterEmptyValidateTable).ValidateUnique(result); - ValidateTable(ItemMasterEmptyValidateTable.All, database, "ItemId", ItemMasterEmptyValidateTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SequentialCheckMasterTable).ValidateUnique(result); - ValidateTable(SequentialCheckMasterTable.All, database, "Id", SequentialCheckMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SingleMasterTable).ValidateUnique(result); - ValidateTable(SingleMasterTable.All, database, "Id", SingleMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)FailTable).ValidateUnique(result); - ValidateTable(FailTable.All, database, "Id", FailTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SampleTable).ValidateUnique(result); - ValidateTable(SampleTable.All, database, "Id", SampleTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SkillMasterTable).ValidateUnique(result); - ValidateTable(SkillMasterTable.All, database, "(SkillId, SkillLevel)", SkillMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)TestMasterTable).ValidateUnique(result); - ValidateTable(TestMasterTable.All, database, "TestID", TestMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)UserLevelTable).ValidateUnique(result); - ValidateTable(UserLevelTable.All, database, "Level", UserLevelTable.PrimaryKeySelector, result); - - return result; - } - - static MasterMemory.Meta.MetaDatabase metaTable; - - public static object GetTable(MemoryDatabase db, string tableName) - { - switch (tableName) - { - case "people": - return db.PersonModelTable; - case "quest_master": - return db.QuestMasterTable; - case "item_master": - return db.ItemMasterTable; - case "quest_master_empty": - return db.QuestMasterEmptyValidateTable; - case "item_master_empty": - return db.ItemMasterEmptyValidateTable; - case "sequantial_master": - return db.SequentialCheckMasterTable; - case "single_master": - return db.SingleMasterTable; - case "fail": - return db.FailTable; - case "s_a_m_p_l_e": - return db.SampleTable; - case "skillmaster": - return db.SkillMasterTable; - case "TestMaster": - return db.TestMasterTable; - case "UserLevel": - return db.UserLevelTable; - - default: - return null; - } - } - - public static MasterMemory.Meta.MetaDatabase GetMetaDatabase() - { - if (metaTable != null) return metaTable; - - var dict = new Dictionary(); - dict.Add("people", MasterMemory.Tests.Tables.PersonModelTable.CreateMetaTable()); - dict.Add("quest_master", MasterMemory.Tests.Tables.QuestMasterTable.CreateMetaTable()); - dict.Add("item_master", MasterMemory.Tests.Tables.ItemMasterTable.CreateMetaTable()); - dict.Add("quest_master_empty", MasterMemory.Tests.Tables.QuestMasterEmptyValidateTable.CreateMetaTable()); - dict.Add("item_master_empty", MasterMemory.Tests.Tables.ItemMasterEmptyValidateTable.CreateMetaTable()); - dict.Add("sequantial_master", MasterMemory.Tests.Tables.SequentialCheckMasterTable.CreateMetaTable()); - dict.Add("single_master", MasterMemory.Tests.Tables.SingleMasterTable.CreateMetaTable()); - dict.Add("fail", MasterMemory.Tests.Tables.FailTable.CreateMetaTable()); - dict.Add("s_a_m_p_l_e", MasterMemory.Tests.Tables.SampleTable.CreateMetaTable()); - dict.Add("skillmaster", MasterMemory.Tests.Tables.SkillMasterTable.CreateMetaTable()); - dict.Add("TestMaster", MasterMemory.Tests.Tables.TestMasterTable.CreateMetaTable()); - dict.Add("UserLevel", MasterMemory.Tests.Tables.UserLevelTable.CreateMetaTable()); - - metaTable = new MasterMemory.Meta.MetaDatabase(dict); - return metaTable; - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/MemoryDatabase.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/MemoryDatabase.cs.meta deleted file mode 100644 index 6c3b732..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/MemoryDatabase.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eed7db8a85de32843bb2560c87d7ee87 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/MessagePackGenerated.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/MessagePackGenerated.cs deleted file mode 100644 index b871bbd..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/MessagePackGenerated.cs +++ /dev/null @@ -1,1114 +0,0 @@ -// -// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT. -// - -#pragma warning disable 618 -#pragma warning disable 612 -#pragma warning disable 414 -#pragma warning disable 168 - -#pragma warning disable SA1200 // Using directives should be placed correctly -#pragma warning disable SA1312 // Variable names should begin with lower-case letter -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Resolvers -{ - using System; - using System.Buffers; - using MessagePack; - - public class GeneratedResolver : global::MessagePack.IFormatterResolver - { - public static readonly global::MessagePack.IFormatterResolver Instance = new GeneratedResolver(); - - private GeneratedResolver() - { - } - - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly global::MessagePack.Formatters.IMessagePackFormatter Formatter; - - static FormatterCache() - { - var f = GeneratedResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (f != null) - { - Formatter = (global::MessagePack.Formatters.IMessagePackFormatter)f; - } - } - } - } - - internal static class GeneratedResolverGetFormatterHelper - { - private static readonly global::System.Collections.Generic.Dictionary lookup; - - static GeneratedResolverGetFormatterHelper() - { - lookup = new global::System.Collections.Generic.Dictionary(11) - { - { typeof(global::MasterMemory.Tests.TestStructures.QuestMaster), 0 }, - { typeof(global::MasterMemory.Tests.TestStructures.ItemMaster), 1 }, - { typeof(global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate), 2 }, - { typeof(global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate), 3 }, - { typeof(global::MasterMemory.Tests.TestStructures.SequentialCheckMaster), 4 }, - { typeof(global::MasterMemory.Tests.TestStructures.SingleMaster), 5 }, - { typeof(global::MasterMemory.Tests.TestStructures.Fail), 6 }, - { typeof(global::MasterMemory.Tests.Sample), 7 }, - { typeof(global::MasterMemory.Tests.SkillMaster), 8 }, - { typeof(global::MasterMemory.Tests.TestStructures.TestMaster), 9 }, - { typeof(global::MasterMemory.Tests.UserLevel), 10 }, - }; - } - - internal static object GetFormatter(Type t) - { - int key; - if (!lookup.TryGetValue(t, out key)) - { - return null; - } - - switch (key) - { - case 0: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.QuestMasterFormatter(); - case 1: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.ItemMasterFormatter(); - case 2: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.QuestMasterEmptyValidateFormatter(); - case 3: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.ItemMasterEmptyValidateFormatter(); - case 4: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.SequentialCheckMasterFormatter(); - case 5: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.SingleMasterFormatter(); - case 6: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.FailFormatter(); - case 7: return new MessagePack.Formatters.MasterMemory.Tests.SampleFormatter(); - case 8: return new MessagePack.Formatters.MasterMemory.Tests.SkillMasterFormatter(); - case 9: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.TestMasterFormatter(); - case 10: return new MessagePack.Formatters.MasterMemory.Tests.UserLevelFormatter(); - default: return null; - } - } - } -} - -#pragma warning restore 168 -#pragma warning restore 414 -#pragma warning restore 618 -#pragma warning restore 612 - -#pragma warning restore SA1312 // Variable names should begin with lower-case letter -#pragma warning restore SA1200 // Using directives should be placed correctly -#pragma warning restore SA1649 // File name should match first type name - - - - -// -// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT. -// - -#pragma warning disable 618 -#pragma warning disable 612 -#pragma warning disable 414 -#pragma warning disable 168 - -#pragma warning disable SA1129 // Do not use default value type constructor -#pragma warning disable SA1200 // Using directives should be placed correctly -#pragma warning disable SA1309 // Field names should not begin with underscore -#pragma warning disable SA1312 // Variable names should begin with lower-case letter -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters.MasterMemory.Tests.TestStructures -{ - using System; - using System.Buffers; - using MessagePack; - - public sealed class QuestMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public QuestMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "QuestId", 0 }, - { "Name", 1 }, - { "RewardItemId", 2 }, - { "Cost", 3 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("QuestId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Name"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("RewardItemId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Cost"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.QuestMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(4); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.QuestId); - writer.WriteRaw(this.____stringByteKeys[1]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.Name, options); - writer.WriteRaw(this.____stringByteKeys[2]); - writer.Write(value.RewardItemId); - writer.WriteRaw(this.____stringByteKeys[3]); - writer.Write(value.Cost); - } - - public global::MasterMemory.Tests.TestStructures.QuestMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __QuestId__ = default(int); - var __Name__ = default(string); - var __RewardItemId__ = default(int); - var __Cost__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __QuestId__ = reader.ReadInt32(); - break; - case 1: - __Name__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __RewardItemId__ = reader.ReadInt32(); - break; - case 3: - __Cost__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.QuestMaster(); - ____result.QuestId = __QuestId__; - ____result.Name = __Name__; - ____result.RewardItemId = __RewardItemId__; - ____result.Cost = __Cost__; - return ____result; - } - } - - public sealed class ItemMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public ItemMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "ItemId", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("ItemId"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.ItemMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.ItemId); - } - - public global::MasterMemory.Tests.TestStructures.ItemMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __ItemId__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __ItemId__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.ItemMaster(); - ____result.ItemId = __ItemId__; - return ____result; - } - } - - public sealed class QuestMasterEmptyValidateFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public QuestMasterEmptyValidateFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "QuestId", 0 }, - { "Name", 1 }, - { "RewardItemId", 2 }, - { "Cost", 3 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("QuestId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Name"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("RewardItemId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Cost"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(4); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.QuestId); - writer.WriteRaw(this.____stringByteKeys[1]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.Name, options); - writer.WriteRaw(this.____stringByteKeys[2]); - writer.Write(value.RewardItemId); - writer.WriteRaw(this.____stringByteKeys[3]); - writer.Write(value.Cost); - } - - public global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __QuestId__ = default(int); - var __Name__ = default(string); - var __RewardItemId__ = default(int); - var __Cost__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __QuestId__ = reader.ReadInt32(); - break; - case 1: - __Name__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __RewardItemId__ = reader.ReadInt32(); - break; - case 3: - __Cost__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate(); - ____result.QuestId = __QuestId__; - ____result.Name = __Name__; - ____result.RewardItemId = __RewardItemId__; - ____result.Cost = __Cost__; - return ____result; - } - } - - public sealed class ItemMasterEmptyValidateFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public ItemMasterEmptyValidateFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "ItemId", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("ItemId"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.ItemId); - } - - public global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __ItemId__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __ItemId__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate(); - ____result.ItemId = __ItemId__; - return ____result; - } - } - - public sealed class SequentialCheckMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SequentialCheckMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - { "Cost", 1 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Cost"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.SequentialCheckMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(2); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Cost); - } - - public global::MasterMemory.Tests.TestStructures.SequentialCheckMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - var __Cost__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - case 1: - __Cost__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.SequentialCheckMaster(); - ____result.Id = __Id__; - ____result.Cost = __Cost__; - return ____result; - } - } - - public sealed class SingleMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SingleMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.SingleMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - } - - public global::MasterMemory.Tests.TestStructures.SingleMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.SingleMaster(); - ____result.Id = __Id__; - return ____result; - } - } - - public sealed class FailFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public FailFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.Fail value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - } - - public global::MasterMemory.Tests.TestStructures.Fail Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.Fail(); - ____result.Id = __Id__; - return ____result; - } - } - - public sealed class TestMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public TestMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "TestID", 0 }, - { "Value", 1 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("TestID"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Value"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.TestMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(2); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.TestID); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Value); - } - - public global::MasterMemory.Tests.TestStructures.TestMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __TestID__ = default(int); - var __Value__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __TestID__ = reader.ReadInt32(); - break; - case 1: - __Value__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.TestMaster(__TestID__, __Value__); - ____result.TestID = __TestID__; - ____result.Value = __Value__; - return ____result; - } - } -} - -#pragma warning restore 168 -#pragma warning restore 414 -#pragma warning restore 618 -#pragma warning restore 612 - -#pragma warning restore SA1129 // Do not use default value type constructor -#pragma warning restore SA1200 // Using directives should be placed correctly -#pragma warning restore SA1309 // Field names should not begin with underscore -#pragma warning restore SA1312 // Variable names should begin with lower-case letter -#pragma warning restore SA1403 // File may only contain a single namespace -#pragma warning restore SA1649 // File name should match first type name - -// -// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT. -// - -#pragma warning disable 618 -#pragma warning disable 612 -#pragma warning disable 414 -#pragma warning disable 168 - -#pragma warning disable SA1129 // Do not use default value type constructor -#pragma warning disable SA1200 // Using directives should be placed correctly -#pragma warning disable SA1309 // Field names should not begin with underscore -#pragma warning disable SA1312 // Variable names should begin with lower-case letter -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters.MasterMemory.Tests -{ - using System; - using System.Buffers; - using MessagePack; - - public sealed class SampleFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SampleFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - { "Age", 1 }, - { "FirstName", 2 }, - { "LastName", 3 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Age"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("FirstName"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("LastName"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.Sample value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(4); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Age); - writer.WriteRaw(this.____stringByteKeys[2]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.FirstName, options); - writer.WriteRaw(this.____stringByteKeys[3]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.LastName, options); - } - - public global::MasterMemory.Tests.Sample Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - var __Age__ = default(int); - var __FirstName__ = default(string); - var __LastName__ = default(string); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - case 1: - __Age__ = reader.ReadInt32(); - break; - case 2: - __FirstName__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 3: - __LastName__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.Sample(__Id__, __Age__, __FirstName__, __LastName__); - ____result.Id = __Id__; - ____result.Age = __Age__; - ____result.FirstName = __FirstName__; - ____result.LastName = __LastName__; - return ____result; - } - } - - public sealed class SkillMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SkillMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "SkillId", 0 }, - { "SkillLevel", 1 }, - { "AttackPower", 2 }, - { "SkillName", 3 }, - { "Description", 4 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("SkillId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("SkillLevel"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("AttackPower"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("SkillName"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Description"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.SkillMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(5); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.SkillId); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.SkillLevel); - writer.WriteRaw(this.____stringByteKeys[2]); - writer.Write(value.AttackPower); - writer.WriteRaw(this.____stringByteKeys[3]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.SkillName, options); - writer.WriteRaw(this.____stringByteKeys[4]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.Description, options); - } - - public global::MasterMemory.Tests.SkillMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __SkillId__ = default(int); - var __SkillLevel__ = default(int); - var __AttackPower__ = default(int); - var __SkillName__ = default(string); - var __Description__ = default(string); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __SkillId__ = reader.ReadInt32(); - break; - case 1: - __SkillLevel__ = reader.ReadInt32(); - break; - case 2: - __AttackPower__ = reader.ReadInt32(); - break; - case 3: - __SkillName__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 4: - __Description__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.SkillMaster(__SkillId__, __SkillLevel__, __AttackPower__, __SkillName__, __Description__); - ____result.SkillId = __SkillId__; - ____result.SkillLevel = __SkillLevel__; - ____result.AttackPower = __AttackPower__; - ____result.SkillName = __SkillName__; - ____result.Description = __Description__; - return ____result; - } - } - - public sealed class UserLevelFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public UserLevelFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Level", 0 }, - { "Exp", 1 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Level"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Exp"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.UserLevel value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(2); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Level); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Exp); - } - - public global::MasterMemory.Tests.UserLevel Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Level__ = default(int); - var __Exp__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Level__ = reader.ReadInt32(); - break; - case 1: - __Exp__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.UserLevel(__Level__, __Exp__); - ____result.Level = __Level__; - ____result.Exp = __Exp__; - return ____result; - } - } -} - -#pragma warning restore 168 -#pragma warning restore 414 -#pragma warning restore 618 -#pragma warning restore 612 - -#pragma warning restore SA1129 // Do not use default value type constructor -#pragma warning restore SA1200 // Using directives should be placed correctly -#pragma warning restore SA1309 // Field names should not begin with underscore -#pragma warning restore SA1312 // Variable names should begin with lower-case letter -#pragma warning restore SA1403 // File may only contain a single namespace -#pragma warning restore SA1649 // File name should match first type name - diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/MessagePackGenerated.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/MessagePackGenerated.cs.meta deleted file mode 100644 index 460ed4a..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/MessagePackGenerated.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 45ad269f5f766e047af975ae678d56f8 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables.meta deleted file mode 100644 index 996bcf2..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 96c5e1d474134e84bb1985289773bcbf -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/FailTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/FailTable.cs deleted file mode 100644 index 51b8784..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/FailTable.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class FailTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public FailTable(Fail[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Fail FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Fail result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Fail FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Fail), typeof(FailTable), "fail", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Fail).GetProperty("Id")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Fail).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/FailTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/FailTable.cs.meta deleted file mode 100644 index 57e5175..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/FailTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ee747dcf2cc8c7d499f84d7005557f76 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs deleted file mode 100644 index 58935ef..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class ItemMasterEmptyValidateTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public ItemMasterEmptyValidateTable(ItemMasterEmptyValidate[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.ItemId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public ItemMasterEmptyValidate FindByItemId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByItemId(int key, out ItemMasterEmptyValidate result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public ItemMasterEmptyValidate FindClosestByItemId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByItemId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "ItemId", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(ItemMasterEmptyValidate), typeof(ItemMasterEmptyValidateTable), "item_master_empty", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(ItemMasterEmptyValidate).GetProperty("ItemId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(ItemMasterEmptyValidate).GetProperty("ItemId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs.meta deleted file mode 100644 index fa3227d..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5b976decd026ca44fb9a4646c6a8a087 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterTable.cs deleted file mode 100644 index 89029a0..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterTable.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class ItemMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public ItemMasterTable(ItemMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.ItemId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public ItemMaster FindByItemId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByItemId(int key, out ItemMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public ItemMaster FindClosestByItemId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByItemId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "ItemId", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(ItemMaster), typeof(ItemMasterTable), "item_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(ItemMaster).GetProperty("ItemId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(ItemMaster).GetProperty("ItemId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterTable.cs.meta deleted file mode 100644 index daba436..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/ItemMasterTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 01945c78ae649d443aec417e8df75425 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/PersonModelTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/PersonModelTable.cs deleted file mode 100644 index d28cbb4..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/PersonModelTable.cs +++ /dev/null @@ -1,140 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class PersonModelTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly PersonModel[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - readonly PersonModel[] secondaryIndex1; - readonly Func secondaryIndex1Selector; - readonly PersonModel[] secondaryIndex2; - readonly Func secondaryIndex2Selector; - - public PersonModelTable(PersonModel[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.RandomId; - this.secondaryIndex0Selector = x => x.LastName; - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.StringComparer.Ordinal); - this.secondaryIndex1Selector = x => (x.FirstName, x.LastName); - this.secondaryIndex1 = CloneAndSortBy(this.secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default); - this.secondaryIndex2Selector = x => x.FirstName; - this.secondaryIndex2 = CloneAndSortBy(this.secondaryIndex2Selector, System.StringComparer.Ordinal); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByLastName => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - public RangeView SortByFirstNameAndLastName => new RangeView(secondaryIndex1, 0, secondaryIndex1.Length - 1, true); - public RangeView SortByFirstName => new RangeView(secondaryIndex2, 0, secondaryIndex2.Length - 1, true); - - public PersonModel FindByRandomId(string key) - { - return FindUniqueCore(data, primaryIndexSelector, System.StringComparer.Ordinal, key, true); - } - - public bool TryFindByRandomId(string key, out PersonModel result) - { - return TryFindUniqueCore(data, primaryIndexSelector, System.StringComparer.Ordinal, key, out result); - } - - public PersonModel FindClosestByRandomId(string key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByRandomId(string min, string max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.StringComparer.Ordinal, min, max, ascendant); - } - - public RangeView FindByLastName(string key) - { - return FindManyCore(secondaryIndex0, secondaryIndex0Selector, System.StringComparer.Ordinal, key); - } - - public RangeView FindClosestByLastName(string key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex0, secondaryIndex0Selector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByLastName(string min, string max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex0, secondaryIndex0Selector, System.StringComparer.Ordinal, min, max, ascendant); - } - - public RangeView FindByFirstNameAndLastName((string FirstName, string LastName) key) - { - return FindManyCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key); - } - - public RangeView FindClosestByFirstNameAndLastName((string FirstName, string LastName) key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, selectLower); - } - - public RangeView FindRangeByFirstNameAndLastName((string FirstName, string LastName) min, (string FirstName, string LastName) max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, min, max, ascendant); - } - - public RangeView FindByFirstName(string key) - { - return FindManyCore(secondaryIndex2, secondaryIndex2Selector, System.StringComparer.Ordinal, key); - } - - public RangeView FindClosestByFirstName(string key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex2, secondaryIndex2Selector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByFirstName(string min, string max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex2, secondaryIndex2Selector, System.StringComparer.Ordinal, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "RandomId", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(PersonModel), typeof(PersonModelTable), "people", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(PersonModel).GetProperty("LastName")), - new MasterMemory.Meta.MetaProperty(typeof(PersonModel).GetProperty("FirstName")), - new MasterMemory.Meta.MetaProperty(typeof(PersonModel).GetProperty("RandomId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("RandomId"), - }, true, true, System.StringComparer.Ordinal), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("LastName"), - }, false, false, System.StringComparer.Ordinal), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("FirstName"), - typeof(PersonModel).GetProperty("LastName"), - }, false, false, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("FirstName"), - }, false, false, System.StringComparer.Ordinal), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/PersonModelTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/PersonModelTable.cs.meta deleted file mode 100644 index ab64d50..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/PersonModelTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1b1388f6febca3e44927effc7b01cb7d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs deleted file mode 100644 index 279ee11..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class QuestMasterEmptyValidateTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public QuestMasterEmptyValidateTable(QuestMasterEmptyValidate[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.QuestId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public QuestMasterEmptyValidate FindByQuestId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByQuestId(int key, out QuestMasterEmptyValidate result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public QuestMasterEmptyValidate FindClosestByQuestId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByQuestId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "QuestId", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(QuestMasterEmptyValidate), typeof(QuestMasterEmptyValidateTable), "quest_master_empty", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("QuestId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("Name")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("RewardItemId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("Cost")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(QuestMasterEmptyValidate).GetProperty("QuestId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs.meta deleted file mode 100644 index 38fc085..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 018ab8246a41b554c819b7e56730a927 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterTable.cs deleted file mode 100644 index bd976dc..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterTable.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class QuestMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public QuestMasterTable(QuestMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.QuestId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public QuestMaster FindByQuestId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByQuestId(int key, out QuestMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public QuestMaster FindClosestByQuestId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByQuestId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "QuestId", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(QuestMaster), typeof(QuestMasterTable), "quest_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("QuestId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("Name")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("RewardItemId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("Cost")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(QuestMaster).GetProperty("QuestId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterTable.cs.meta deleted file mode 100644 index c54cf3b..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/QuestMasterTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9cfdf1b308bbd524f9f46ae80b9ce23a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SampleTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SampleTable.cs deleted file mode 100644 index b6a458c..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SampleTable.cs +++ /dev/null @@ -1,289 +0,0 @@ -// -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SampleTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly Sample[] secondaryIndex1; - readonly Func secondaryIndex1Selector; - readonly Sample[] secondaryIndex2; - readonly Func secondaryIndex2Selector; - readonly Sample[] secondaryIndex3; - readonly Func secondaryIndex3Selector; - readonly Sample[] secondaryIndex5; - readonly Func secondaryIndex5Selector; - readonly Sample[] secondaryIndex6; - readonly Func secondaryIndex6Selector; - readonly Sample[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - readonly Sample[] secondaryIndex4; - readonly Func secondaryIndex4Selector; - - public SampleTable(Sample[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - this.secondaryIndex1Selector = x => (x.Id, x.Age, x.FirstName, x.LastName); - this.secondaryIndex1 = CloneAndSortBy(this.secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default); - this.secondaryIndex2Selector = x => (x.Id, x.Age); - this.secondaryIndex2 = CloneAndSortBy(this.secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default); - this.secondaryIndex3Selector = x => (x.Id, x.Age, x.FirstName); - this.secondaryIndex3 = CloneAndSortBy(this.secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default); - this.secondaryIndex5Selector = x => x.Age; - this.secondaryIndex5 = CloneAndSortBy(this.secondaryIndex5Selector, System.Collections.Generic.Comparer.Default); - this.secondaryIndex6Selector = x => (x.FirstName, x.Age); - this.secondaryIndex6 = CloneAndSortBy(this.secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default); - this.secondaryIndex0Selector = x => (x.FirstName, x.LastName); - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default); - this.secondaryIndex4Selector = x => x.FirstName; - this.secondaryIndex4 = CloneAndSortBy(this.secondaryIndex4Selector, System.StringComparer.Ordinal); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByIdAndAgeAndFirstNameAndLastName => new RangeView(secondaryIndex1, 0, secondaryIndex1.Length - 1, true); - public RangeView SortByIdAndAge => new RangeView(secondaryIndex2, 0, secondaryIndex2.Length - 1, true); - public RangeView SortByIdAndAgeAndFirstName => new RangeView(secondaryIndex3, 0, secondaryIndex3.Length - 1, true); - public RangeView SortByAge => new RangeView(secondaryIndex5, 0, secondaryIndex5.Length - 1, true); - public RangeView SortByFirstNameAndAge => new RangeView(secondaryIndex6, 0, secondaryIndex6.Length - 1, true); - public RangeView SortByFirstNameAndLastName => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - public RangeView SortByFirstName => new RangeView(secondaryIndex4, 0, secondaryIndex4.Length - 1, true); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Sample FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Sample result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Sample FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public Sample FindByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) key) - { - return FindUniqueCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, key, true); - } - - public bool TryFindByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, key, out result); - } - - public Sample FindClosestByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, key, selectLower); - } - - public RangeView FindRangeByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) min, (int Id, int Age, string FirstName, string LastName) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, min, max, ascendant); - } - - public Sample FindByIdAndAge((int Id, int Age) key) - { - return FindUniqueCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, key, true); - } - - public bool TryFindByIdAndAge((int Id, int Age) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, key, out result); - } - - public Sample FindClosestByIdAndAge((int Id, int Age) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, key, selectLower); - } - - public RangeView FindRangeByIdAndAge((int Id, int Age) min, (int Id, int Age) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, min, max, ascendant); - } - - public Sample FindByIdAndAgeAndFirstName((int Id, int Age, string FirstName) key) - { - return FindUniqueCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, key, true); - } - - public bool TryFindByIdAndAgeAndFirstName((int Id, int Age, string FirstName) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, key, out result); - } - - public Sample FindClosestByIdAndAgeAndFirstName((int Id, int Age, string FirstName) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, key, selectLower); - } - - public RangeView FindRangeByIdAndAgeAndFirstName((int Id, int Age, string FirstName) min, (int Id, int Age, string FirstName) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, min, max, ascendant); - } - - public RangeView FindByAge(int key) - { - return FindManyCore(secondaryIndex5, secondaryIndex5Selector, System.Collections.Generic.Comparer.Default, key); - } - - public RangeView FindClosestByAge(int key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex5, secondaryIndex5Selector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByAge(int min, int max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex5, secondaryIndex5Selector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public RangeView FindByFirstNameAndAge((string FirstName, int Age) key) - { - return FindManyCore(secondaryIndex6, secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default, key); - } - - public RangeView FindClosestByFirstNameAndAge((string FirstName, int Age) key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex6, secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default, key, selectLower); - } - - public RangeView FindRangeByFirstNameAndAge((string FirstName, int Age) min, (string FirstName, int Age) max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex6, secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default, min, max, ascendant); - } - - public Sample FindByFirstNameAndLastName((string FirstName, string LastName) key) - { - return FindUniqueCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, true); - } - - public bool TryFindByFirstNameAndLastName((string FirstName, string LastName) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, out result); - } - - public Sample FindClosestByFirstNameAndLastName((string FirstName, string LastName) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, selectLower); - } - - public RangeView FindRangeByFirstNameAndLastName((string FirstName, string LastName) min, (string FirstName, string LastName) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, min, max, ascendant); - } - - public RangeView FindByFirstName(string key) - { - return FindManyCore(secondaryIndex4, secondaryIndex4Selector, System.StringComparer.Ordinal, key); - } - - public RangeView FindClosestByFirstName(string key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex4, secondaryIndex4Selector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByFirstName(string min, string max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex4, secondaryIndex4Selector, System.StringComparer.Ordinal, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - ValidateUniqueCore(secondaryIndex1, secondaryIndex1Selector, "(Id, Age, FirstName, LastName)", resultSet); - ValidateUniqueCore(secondaryIndex2, secondaryIndex2Selector, "(Id, Age)", resultSet); - ValidateUniqueCore(secondaryIndex3, secondaryIndex3Selector, "(Id, Age, FirstName)", resultSet); - ValidateUniqueCore(secondaryIndex0, secondaryIndex0Selector, "(FirstName, LastName)", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Sample), typeof(SampleTable), "s_a_m_p_l_e", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("Id")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("Age")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("FirstName")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("LastName")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("Hoge")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - typeof(Sample).GetProperty("Age"), - typeof(Sample).GetProperty("FirstName"), - typeof(Sample).GetProperty("LastName"), - }, false, true, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - typeof(Sample).GetProperty("Age"), - }, false, true, System.Collections.Generic.Comparer<(int Id, int Age)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - typeof(Sample).GetProperty("Age"), - typeof(Sample).GetProperty("FirstName"), - }, false, true, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Age"), - }, false, false, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("FirstName"), - typeof(Sample).GetProperty("Age"), - }, false, false, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("FirstName"), - typeof(Sample).GetProperty("LastName"), - }, false, true, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("FirstName"), - }, false, false, System.StringComparer.Ordinal), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SampleTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SampleTable.cs.meta deleted file mode 100644 index ac9aaa2..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SampleTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 50650027bb1baa5418bc1be37483ce91 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SequentialCheckMasterTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SequentialCheckMasterTable.cs deleted file mode 100644 index 99fd1a1..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SequentialCheckMasterTable.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SequentialCheckMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public SequentialCheckMasterTable(SequentialCheckMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public SequentialCheckMaster FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out SequentialCheckMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public SequentialCheckMaster FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(SequentialCheckMaster), typeof(SequentialCheckMasterTable), "sequantial_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(SequentialCheckMaster).GetProperty("Id")), - new MasterMemory.Meta.MetaProperty(typeof(SequentialCheckMaster).GetProperty("Cost")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(SequentialCheckMaster).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SequentialCheckMasterTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SequentialCheckMasterTable.cs.meta deleted file mode 100644 index 844ee22..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SequentialCheckMasterTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: be062ae259769744f92de9dc952b9154 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SingleMasterTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SingleMasterTable.cs deleted file mode 100644 index 6a1e00d..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SingleMasterTable.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SingleMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public SingleMasterTable(SingleMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public SingleMaster FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out SingleMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public SingleMaster FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(SingleMaster), typeof(SingleMasterTable), "single_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(SingleMaster).GetProperty("Id")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(SingleMaster).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SingleMasterTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SingleMasterTable.cs.meta deleted file mode 100644 index a3ae8dc..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SingleMasterTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5314971362d66d748b568c830985b4fb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SkillMasterTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SkillMasterTable.cs deleted file mode 100644 index a9bc0e9..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SkillMasterTable.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SkillMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public SkillMasterTable(SkillMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => (x.SkillId, x.SkillLevel); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - public SkillMaster FindBySkillIdAndSkillLevel((int SkillId, int SkillLevel) key) - { - return FindUniqueCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, key, true); - } - - public bool TryFindBySkillIdAndSkillLevel((int SkillId, int SkillLevel) key, out SkillMaster result) - { - return TryFindUniqueCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, key, out result); - } - - public SkillMaster FindClosestBySkillIdAndSkillLevel((int SkillId, int SkillLevel) key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, key, selectLower); - } - - public RangeView FindRangeBySkillIdAndSkillLevel((int SkillId, int SkillLevel) min, (int SkillId, int SkillLevel) max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "(SkillId, SkillLevel)", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(SkillMaster), typeof(SkillMasterTable), "skillmaster", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("SkillId")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("SkillLevel")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("AttackPower")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("SkillName")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("Description")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(SkillMaster).GetProperty("SkillId"), - typeof(SkillMaster).GetProperty("SkillLevel"), - }, true, true, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SkillMasterTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SkillMasterTable.cs.meta deleted file mode 100644 index e4f99a0..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/SkillMasterTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b8e5d6b9ced727947b01b00d46ba6af7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/TestMasterTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/TestMasterTable.cs deleted file mode 100644 index 6e1dca4..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/TestMasterTable.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class TestMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public TestMasterTable(TestMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.TestID; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - public RangeView FindByTestID(int key) - { - return FindManyCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key); - } - - public RangeView FindClosestByTestID(int key, bool selectLower = true) - { - return FindManyClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByTestID(int min, int max, bool ascendant = true) - { - return FindManyRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(TestMaster), typeof(TestMasterTable), "TestMaster", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(TestMaster).GetProperty("TestID")), - new MasterMemory.Meta.MetaProperty(typeof(TestMaster).GetProperty("Value")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(TestMaster).GetProperty("TestID"), - }, true, false, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/TestMasterTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/TestMasterTable.cs.meta deleted file mode 100644 index cad6d96..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/TestMasterTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5a2a0d5553b0f6c448a209794fb85f94 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/UserLevelTable.cs b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/UserLevelTable.cs deleted file mode 100644 index 18988c6..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/UserLevelTable.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class UserLevelTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly UserLevel[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - - public UserLevelTable(UserLevel[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Level; - this.secondaryIndex0Selector = x => x.Exp; - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.Collections.Generic.Comparer.Default); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByExp => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public UserLevel FindByLevel(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Level; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByLevel(int key, out UserLevel result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Level; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public UserLevel FindClosestByLevel(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByLevel(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public UserLevel FindByExp(int key) - { - return FindUniqueCoreInt(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, true); - } - - public bool TryFindByExp(int key, out UserLevel result) - { - return TryFindUniqueCoreInt(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, out result); - } - - public UserLevel FindClosestByExp(int key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByExp(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { - ValidateUniqueCore(data, primaryIndexSelector, "Level", resultSet); - ValidateUniqueCore(secondaryIndex0, secondaryIndex0Selector, "Exp", resultSet); - } - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(UserLevel), typeof(UserLevelTable), "UserLevel", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(UserLevel).GetProperty("Level")), - new MasterMemory.Meta.MetaProperty(typeof(UserLevel).GetProperty("Exp")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(UserLevel).GetProperty("Level"), - }, true, true, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(UserLevel).GetProperty("Exp"), - }, false, true, System.Collections.Generic.Comparer.Default), - }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/UserLevelTable.cs.meta b/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/UserLevelTable.cs.meta deleted file mode 100644 index da1d2d8..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/Generated/Tables/UserLevelTable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f18f91b49d0505a4691d2f69490be062 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/IssueTest.cs b/src/MasterMemory.Unity/Assets/Tests/IssueTest.cs deleted file mode 100644 index d81b0e6..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/IssueTest.cs +++ /dev/null @@ -1,67 +0,0 @@ -using FluentAssertions; -using MasterMemory.Tests.TestStructures; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Xunit; - -namespace MasterMemory.Tests -{ - public class IssueTest - { - //[Fact] - //public void Issue49() - //{ - // var builder = new DatabaseBuilder().Append(new[] - // { - // new PersonModel { FirstName = "realname", LastName="reallast" }, - // new PersonModel { FirstName = "fakefirst", LastName="fakelast" }, - // }); - - // var data = builder.Build(); - // var database = new MemoryDatabase(data); - - // var entries = database.PersonModelTable.FindClosestByFirstNameAndLastName(("real", "real"), false); - // var firstEntry = entries.FirstOrDefault(); - - // var firstIs = firstEntry.FirstName; - - //} - - Sample[] CreateData() - { - // Id = Unique, PK - // FirstName + LastName = Unique - var data = new[] - { - new Sample { Id = 5, Age = 19, FirstName = "aaa", LastName = "foo" }, - new Sample { Id = 6, Age = 29, FirstName = "bbb", LastName = "foo" }, - new Sample { Id = 7, Age = 39, FirstName = "ccc", LastName = "foo" }, - new Sample { Id = 8, Age = 49, FirstName = "ddd", LastName = "foo" }, - new Sample { Id = 1, Age = 59, FirstName = "eee", LastName = "foo" }, - new Sample { Id = 2, Age = 89, FirstName = "aaa", LastName = "bar" }, - new Sample { Id = 3, Age = 79, FirstName = "be", LastName = "de" }, - new Sample { Id = 4, Age = 89, FirstName = "aaa", LastName = "tako" }, - new Sample { Id = 9, Age = 99, FirstName = "aaa", LastName = "ika" }, - new Sample { Id = 10, Age = 9, FirstName = "eee", LastName = "baz" }, - }; - return data; - } - - [Fact] - public void Issue57() - { - var builder = new DatabaseBuilder(); - builder.Append(CreateData()); - - var bin = builder.Build(); - var db = new MemoryDatabase(bin); - - db.SampleTable.FindRangeByAge(2, 2).Select(x => x.Id).ToArray().Should().BeEquivalentTo(new int[] { }); - db.SampleTable.FindRangeByAge(30, 50).Select(x => x.Id).ToArray().Should().BeEquivalentTo(new int[] { 7, 8 }); - db.SampleTable.FindRangeByAge(100, 100).Select(x => x.Id).ToArray().Should().BeEquivalentTo(new int[] { }); - } - - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/IssueTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/IssueTest.cs.meta deleted file mode 100644 index 96062c2..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/IssueTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 826c21784d299f44b8f6b64eaaf2ed57 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/MasterMemory.Tests.asmdef b/src/MasterMemory.Unity/Assets/Tests/MasterMemory.Tests.asmdef deleted file mode 100644 index f3226a2..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MasterMemory.Tests.asmdef +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "MasterMemory.Tests", - "references": [ - "MasterMemory", - "MessagePack", - "MessagePack.Annotations" - ], - "optionalUnityReferences": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [] -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/MasterMemory.Tests.asmdef.meta b/src/MasterMemory.Unity/Assets/Tests/MasterMemory.Tests.asmdef.meta deleted file mode 100644 index 0f04706..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MasterMemory.Tests.asmdef.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: b8b409d5c4a9b0d48a2d16252f84b2f1 -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/MemoryKeyTest.cs b/src/MasterMemory.Unity/Assets/Tests/MemoryKeyTest.cs deleted file mode 100644 index 509574d..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MemoryKeyTest.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Xunit; -using System.Linq; -using MasterMemory.Tests.Tables; -using FluentAssertions; -using MessagePack; -using System.Collections.Generic; - -namespace MasterMemory.Tests -{ - public class MemoryKeyMemoryTest - { - public MemoryKeyMemoryTest() - { - MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(MessagePackResolver.Instance); - } - - Sample[] CreateData() - { - // Id = Unique, PK - // FirstName + LastName = Unique - var data = new[] - { - new Sample { Id = 5, Age = 19, FirstName = "aaa", LastName = "foo" }, - new Sample { Id = 6, Age = 29, FirstName = "bbb", LastName = "foo" }, - new Sample { Id = 7, Age = 39, FirstName = "ccc", LastName = "foo" }, - new Sample { Id = 8, Age = 49, FirstName = "ddd", LastName = "foo" }, - new Sample { Id = 1, Age = 59, FirstName = "eee", LastName = "foo" }, - new Sample { Id = 2, Age = 89, FirstName = "aaa", LastName = "bar" }, - new Sample { Id = 3, Age = 79, FirstName = "be", LastName = "de" }, - new Sample { Id = 4, Age = 89, FirstName = "aaa", LastName = "tako" }, - new Sample { Id = 9, Age = 99, FirstName = "aaa", LastName = "ika" }, - new Sample { Id = 10, Age = 9, FirstName = "eee", LastName = "baz" }, - }; - return data; - } - - SampleTable CreateTable() - { - return new MemoryDatabase(new DatabaseBuilder().Append(CreateData()).Build()).SampleTable; - } - - [Fact] - public void Unique() - { - var table = CreateTable(); - - table.FindById(8).Id.Should().Be(8); - Assert.Throws(() => table.FindById(100)); - - table.FindByIdAndAge((4, 89)).Id.Should().Be(4); - - Assert.Throws(() => table.FindByIdAndAge((4, 899))); - Assert.Throws(() => table.FindByIdAndAge((5, 89))); - - table.FindByIdAndAgeAndFirstName((6, 29, "bbb")).Id.Should().Be(6); - Assert.Throws(() => table.FindByIdAndAgeAndFirstName((6, 29, "bbbz"))); - } - - [Fact] - public void Range() - { - var table = CreateTable(); - - var test = table.FindByFirstName("eee"); - - table.FindByFirstName("eee").Select(x => x.Id).OrderBy(x => x).Should().BeEquivalentTo(new[] { 1, 10 }); - table.FindByFirstName("eeee").Count.Should().Be(0); - - table.FindClosestByFirstNameAndLastName(("aaa", "takz")).Id.Should().Be(4); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/MemoryKeyTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/MemoryKeyTest.cs.meta deleted file mode 100644 index 1810cf8..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MemoryKeyTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c6e62b5b0da414d4aa2e7d53e691a31d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/MemoryTest.cs b/src/MasterMemory.Unity/Assets/Tests/MemoryTest.cs deleted file mode 100644 index 83da7f6..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MemoryTest.cs +++ /dev/null @@ -1,189 +0,0 @@ -using FluentAssertions; -using MasterMemory.Tests.Tables; -using MessagePack; -using System.Collections.Generic; -using System.Linq; -using Xunit; - -namespace MasterMemory.Tests -{ - public class MemoryTest - { - public MemoryTest() - { - MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(MessagePackResolver.Instance); - } - - Sample[] CreateData() - { - // Id = Unique, PK - // FirstName + LastName = Unique - var data = new[] - { - new Sample { Id = 5, Age = 19, FirstName = "aaa", LastName = "foo" }, - new Sample { Id = 6, Age = 29, FirstName = "bbb", LastName = "foo" }, - new Sample { Id = 7, Age = 39, FirstName = "ccc", LastName = "foo" }, - new Sample { Id = 8, Age = 49, FirstName = "ddd", LastName = "foo" }, - new Sample { Id = 1, Age = 59, FirstName = "eee", LastName = "foo" }, - new Sample { Id = 2, Age = 89, FirstName = "aaa", LastName = "bar" }, - new Sample { Id = 3, Age = 79, FirstName = "be", LastName = "de" }, - new Sample { Id = 4, Age = 89, FirstName = "aaa", LastName = "tako" }, - new Sample { Id = 9, Age = 99, FirstName = "aaa", LastName = "ika" }, - new Sample { Id = 10, Age = 9, FirstName = "eee", LastName = "baz" }, - }; - return data; - } - - SampleTable CreateTable(Sample[] data) - { - return new MemoryDatabase(new DatabaseBuilder().Append(data).Build()).SampleTable; - } - - [Fact] - public void Count() - { - var data = CreateData(); - var table = CreateTable(data); - - table.Count.Should().Be(data.Length); - } - - [Fact] - public void Find() - { - var data = CreateData(); - var table = CreateTable(data); - - foreach (var item in data) - { - var f = table.FindById(item.Id); - item.Id.Should().Be(f.Id); - } - - Assert.Throws(() => table.FindById(110)); - table.TryFindById(110, out _).Should().BeFalse(); - } - - [Fact] - public void MultiKeyFind() - { - var data = CreateData(); - var table = CreateTable(data); - - foreach (var item in data) - { - var f = table.FindByFirstNameAndLastName((item.FirstName, item.LastName)); - item.Id.Should().Be(f.Id); - } - - Assert.Throws(() => table.FindByFirstNameAndLastName(("aaa", "___"))); - Assert.Throws(() => table.FindByFirstNameAndLastName(("___", "foo"))); - table.TryFindByFirstNameAndLastName(("aaa", "___"), out _).Should().BeFalse(); - table.TryFindByFirstNameAndLastName(("___", "foo"), out _).Should().BeFalse(); - } - - [Fact] - public void FindClosest() - { - var data = CreateData(); - var table = CreateTable(data); - - { - table.FindClosestByAge(56, true).First.Age.Should().Be(49); - table.FindClosestByAge(56, false).First.Age.Should().Be(59); - } - { - // first - for (int i = 0; i < 9; i++) - { - table.FindClosestByAge(i, selectLower: true).Count.Should().Be(0); -// table.FindClosestByAge(i, selectLower: true).First.Age.Should().Be(9); - } - - var lastAge = 9; - foreach (var item in data.OrderBy(x => x.Age)) - { - for (int i = lastAge + 1; i < item.Age; i++) - { - table.FindClosestByAge(i, selectLower: true).First.Age.Should().Be(lastAge); - } - - lastAge = item.Age; - } - - // last - table.FindClosestByAge(99, selectLower: false).First.Age.Should().Be(99); - - for (int i = 100; i < 120; i++) - { - table.FindClosestByAge(i, selectLower: false).Count.Should().Be(0); -// table.FindClosestByAge(i, selectLower: true).First.Age.Should().Be(99); - } - } - { - // first - for (int i = 0; i < 9; i++) - { - table.FindClosestByAge(i, selectLower: false).First.Age.Should().Be(9); - } - - var xss = data.OrderBy(x => x.Age).ToArray(); - for (int j = 1; j < xss.Length - 1; j++) - { - var item = xss[j]; - for (int i = xss[j - 1].Age + 1; i < item.Age; i++) - { - table.FindClosestByAge(i, selectLower: false).First.Age.Should().Be(xss[j].Age); - } - } - - // last - table.FindClosestByAge(99, selectLower: false).First.Age.Should().Be(99); - - for (int i = 100; i < 120; i++) - { - table.FindClosestByAge(i, selectLower: false).Count.Should().Be(0); - } - } - } - - [Fact] - public void FindClosestMultiKey() - { - var data = CreateData(); - var table = CreateTable(data); - - // Age of aaa - //new Sample { Id = 5, Age = 19, FirstName = "aaa", LastName = "foo" }, - //new Sample { Id = 2, Age = 89, FirstName = "aaa", LastName = "bar" }, - //new Sample { Id = 4, Age = 89, FirstName = "aaa", LastName = "tako" }, - //new Sample { Id = 9, Age = 99, FirstName = "aaa", LastName = "ika" }, - - table.FindClosestByFirstNameAndAge(("aaa", 10), true).Count.Should().Be(0); - table.FindClosestByFirstNameAndAge(("aaa", 10), false).First.Age.Should().Be(19); - table.FindClosestByFirstNameAndAge(("aaa", 92), true).First.Age.Should().Be(89); - table.FindClosestByFirstNameAndAge(("aaa", 120), true).First.Age.Should().Be(99); - table.FindClosestByFirstNameAndAge(("aaa", 10), false).First.Age.Should().Be(19); - table.FindClosestByFirstNameAndAge(("aaa", 73), false).First.Age.Should().Be(89); - } - - [Fact] - public void FindMany() - { - var data = CreateData(); - var table = CreateTable(data); - - table.FindByFirstName("aaa").OrderBy(x => x.Id).Select(x => x.Id).Should().BeEquivalentTo(new[] { 2, 4, 5, 9 }); - } - - [Fact] - public void FindManyMultiKey() - { - var data = CreateData(); - var table = CreateTable(data); - - table.FindByFirstNameAndAge(("aaa", 89)).Select(x => x.Id).Should().BeEquivalentTo(new[] { 2, 4 }); - table.FindByFirstNameAndAge(("aaa", 89)).Reverse.Select(x => x.Id).Should().BeEquivalentTo(new[] { 4, 2 }); - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/MemoryTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/MemoryTest.cs.meta deleted file mode 100644 index a8510e3..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MemoryTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6bb3542e7a1c6134fabe798112b89f7f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/MessagePackResolver.cs b/src/MasterMemory.Unity/Assets/Tests/MessagePackResolver.cs deleted file mode 100644 index d223ace..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MessagePackResolver.cs +++ /dev/null @@ -1,26 +0,0 @@ -using MessagePack; -using MessagePack.Formatters; -using MessagePack.Resolvers; -using System; -using System.Collections.Generic; -using System.Text; - -namespace MasterMemory.Tests -{ - public class MessagePackResolver : IFormatterResolver - { - public static IFormatterResolver Instance = new MessagePackResolver(); - - MessagePackResolver() - { - - } - - public IMessagePackFormatter GetFormatter() - { - return MasterMemoryResolver.Instance.GetFormatter() - ?? GeneratedResolver.Instance.GetFormatter() - ?? StandardResolver.Instance.GetFormatter(); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/MessagePackResolver.cs.meta b/src/MasterMemory.Unity/Assets/Tests/MessagePackResolver.cs.meta deleted file mode 100644 index e5938e7..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MessagePackResolver.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9d0e5afd8d4770540bf810c994a214e5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/MetaTest.cs b/src/MasterMemory.Unity/Assets/Tests/MetaTest.cs deleted file mode 100644 index f8e4481..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MetaTest.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using FluentAssertions; -using System.Collections.Generic; -using System.Text; -using Xunit; - -namespace MasterMemory.Tests -{ - public class MetaTest - { - [Fact] - public void Meta() - { - var metaDb = MemoryDatabase.GetMetaDatabase(); - - var sampleTable = metaDb.GetTableInfo("s_a_m_p_l_e"); - - sampleTable.TableName.Should().Be("s_a_m_p_l_e"); - - sampleTable.Properties[0].Name.Should().Be("Id"); - sampleTable.Properties[0].NameLowerCamel.Should().Be("id"); - sampleTable.Properties[0].NameSnakeCase.Should().Be("id"); - - sampleTable.Properties[2].Name.Should().Be("FirstName"); - sampleTable.Properties[2].NameLowerCamel.Should().Be("firstName"); - sampleTable.Properties[2].NameSnakeCase.Should().Be("first_name"); - - var primary = sampleTable.Indexes[0]; - primary.IsUnique.Should().BeTrue(); - primary.IndexProperties[0].Name.Should().Be("Id"); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/MetaTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/MetaTest.cs.meta deleted file mode 100644 index 9d1aef8..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/MetaTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 44f633659c8690748bd8cd21fce3bb38 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/RangeViewTest.cs b/src/MasterMemory.Unity/Assets/Tests/RangeViewTest.cs deleted file mode 100644 index e63c7bf..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/RangeViewTest.cs +++ /dev/null @@ -1,96 +0,0 @@ -using FluentAssertions; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Xunit; - -namespace MasterMemory.Tests -{ - public class RangeViewTest - { - [Fact] - public void Range() - { - // 4 -> 8 - { - var range = new RangeView(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 4, 8, true); - - range.Count.Should().Be(5); - range[0].Should().Be(4); - range[1].Should().Be(5); - range[2].Should().Be(6); - range[3].Should().Be(7); - range[4].Should().Be(8); - - Assert.Throws(() => range[-1]); - Assert.Throws(() => range[5]); - - var begin = 4; - foreach (var item in range) - { - item.Should().Be(begin++); - } - - var xs = new int[10]; - range.CopyTo(xs, 3); - xs[3].Should().Be(4); - xs[4].Should().Be(5); - xs[5].Should().Be(6); - xs[6].Should().Be(7); - xs[7].Should().Be(8); - xs[8].Should().Be(0); - - range.IndexOf(5).Should().Be(1); - range.IndexOf(9).Should().Be(-1); - - - range.Contains(5).Should().BeTrue(); - range.Contains(9).Should().BeFalse(); - } - { - // 7 -> 2 - var range = new RangeView(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, 7, false); - - range.Count.Should().Be(6); - range[0].Should().Be(7); - range[1].Should().Be(6); - range[2].Should().Be(5); - range[3].Should().Be(4); - range[4].Should().Be(3); - range[5].Should().Be(2); - - Assert.Throws(() => range[-1]); - Assert.Throws(() => range[6]); - - var begin = 7; - foreach (var item in range) - { - item.Should().Be(begin--); - } - - var xs = new int[10]; - range.CopyTo(xs, 3); - xs[3].Should().Be(7); - xs[4].Should().Be(6); - xs[5].Should().Be(5); - xs[6].Should().Be(4); - xs[7].Should().Be(3); - xs[8].Should().Be(2); - - range.IndexOf(5).Should().Be(2); - range.IndexOf(9).Should().Be(-1); - - range.Contains(5).Should().BeTrue(); - range.Contains(9).Should().BeFalse(); - } - - var empty = new RangeView(Enumerable.Empty().ToArray(), 0, 0, true); - empty.Count.Should().Be(0); - - var same = new RangeView(Enumerable.Range(1, 1000).ToArray(), 100, 100, true); - same.Count.Should().Be(1); - same[0].Should().Be(101); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/RangeViewTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/RangeViewTest.cs.meta deleted file mode 100644 index 448287e..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/RangeViewTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2f72762922cad0d40bb20c8e3748abfa -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures.meta deleted file mode 100644 index 6d162df..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 3e9f22be720a50944bc3a68bab48e943 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/PersonModel.cs b/src/MasterMemory.Unity/Assets/Tests/TestStructures/PersonModel.cs deleted file mode 100644 index 2abb469..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/PersonModel.cs +++ /dev/null @@ -1,22 +0,0 @@ -using MessagePack; -using System; -using System.Collections.Generic; -using System.Text; - -namespace MasterMemory.Tests.TestStructures -{ - - [MemoryTable("people"), MessagePackObject(true)] - public class PersonModel - { - [SecondaryKey(0), NonUnique] - [SecondaryKey(1, keyOrder: 1), NonUnique] - public string LastName { get; set; } - - [SecondaryKey(2), NonUnique] - [SecondaryKey(1, keyOrder: 0), NonUnique] - public string FirstName { get; set; } - - [PrimaryKey] public string RandomId { get; set; } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/PersonModel.cs.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures/PersonModel.cs.meta deleted file mode 100644 index e49f7e6..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/PersonModel.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 87e2567b7dd010f4eb7f4d18c44a3358 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/QuestMaster.cs b/src/MasterMemory.Unity/Assets/Tests/TestStructures/QuestMaster.cs deleted file mode 100644 index c809e79..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/QuestMaster.cs +++ /dev/null @@ -1,114 +0,0 @@ -using MessagePack; -using System; -using System.Collections.Generic; -using System.Text; - -namespace MasterMemory.Tests.TestStructures -{ - [MemoryTable("quest_master"), MessagePackObject(true)] - public class QuestMaster : IValidatable - { - [PrimaryKey] - public int QuestId { get; set; } - public string Name { get; set; } - public int RewardItemId { get; set; } - public int Cost { get; set; } - - public void Validate(IValidator validator) - { - var itemMaster = validator.GetReferenceSet(); - - itemMaster.Exists(x => x.RewardItemId, x => x.ItemId); - - validator.Validate(x => x.Cost <= 100); - validator.Validate(x => x.Cost >= 0, ">= 0!!!"); - - validator.ValidateAction(() => this.Cost <= 1000); - validator.ValidateAction(() => this.Cost >= -90, ">= -90!!!"); - - if (validator.CallOnce()) - { - var quests = validator.GetTableSet(); - quests.Unique(x => x.Name); - } - } - } - - [MemoryTable("item_master"), MessagePackObject(true)] - public class ItemMaster : IValidatable - { - [PrimaryKey] - public int ItemId { get; set; } - - public void Validate(IValidator validator) - { - } - } - - [MemoryTable("quest_master_empty"), MessagePackObject(true)] - public class QuestMasterEmptyValidate - { - [PrimaryKey] - public int QuestId { get; set; } - public string Name { get; set; } - public int RewardItemId { get; set; } - public int Cost { get; set; } - } - - [MemoryTable("item_master_empty"), MessagePackObject(true)] - public class ItemMasterEmptyValidate - { - [PrimaryKey] - public int ItemId { get; set; } - } - - [MemoryTable("sequantial_master"), MessagePackObject(true)] - public class SequentialCheckMaster : IValidatable - { - [PrimaryKey] - public int Id { get; set; } - public int Cost { get; set; } - - public void Validate(IValidator validator) - { - if (validator.CallOnce()) - { - var set = validator.GetTableSet(); - - set.Sequential(x => x.Id); - set.Sequential(x => x.Cost, true); - } - } - } - - [MemoryTable("single_master"), MessagePackObject(true)] - public class SingleMaster : IValidatable - { - public static int CalledValidateCount; - public static int CalledOnceCount; - - [PrimaryKey] - public int Id { get; set; } - - public void Validate(IValidator validator) - { - CalledValidateCount++; - if (validator.CallOnce()) - { - CalledOnceCount++; - } - } - } - - [MemoryTable("fail"), MessagePackObject(true)] - public class Fail : IValidatable - { - [PrimaryKey] - public int Id { get; set; } - - public void Validate(IValidator validator) - { - validator.Fail("Failed Id:" + Id); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/QuestMaster.cs.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures/QuestMaster.cs.meta deleted file mode 100644 index e768e37..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/QuestMaster.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 388d81044b61b804699a0736c38ca60d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/Sample.cs b/src/MasterMemory.Unity/Assets/Tests/TestStructures/Sample.cs deleted file mode 100644 index f2bc500..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/Sample.cs +++ /dev/null @@ -1,56 +0,0 @@ -using MessagePack; - -namespace MasterMemory.Tests -{ - [MemoryTable("s_a_m_p_l_e"), MessagePackObject(true)] - public class Sample - { - [PrimaryKey] - [SecondaryKey(1)] - [SecondaryKey(2)] - [SecondaryKey(3)] - public int Id { get; set; } - [SecondaryKey(1)] - [SecondaryKey(2)] - [SecondaryKey(3)] - [SecondaryKey(5), NonUnique] - [SecondaryKey(6, 1), NonUnique] - public int Age { get; set; } - [SecondaryKey(0)] - [SecondaryKey(1)] - [SecondaryKey(3)] - [SecondaryKey(4), NonUnique] - [SecondaryKey(6, 0), NonUnique] - public string FirstName { get; set; } - [SecondaryKey(0)] - [SecondaryKey(1)] - public string LastName { get; set; } - - - [MessagePack.IgnoreMember] - public int Hoge { get; set; } - - [System.Runtime.Serialization.IgnoreDataMember] - public int Huga { get; set; } - - public override string ToString() - { - return $"{Id} {Age} {FirstName} {LastName}"; - } - - public Sample() - { - - } - - public Sample(int Id, int Age, string FirstName, string LastName) - { - this.Id = Id; - this.Age = Age; - this.FirstName = FirstName; - this.LastName = LastName; - } - - - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/Sample.cs.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures/Sample.cs.meta deleted file mode 100644 index d0f0f7d..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/Sample.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9282e5a5464bebe4eabdbe217ebcc930 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/SkillMaster.cs b/src/MasterMemory.Unity/Assets/Tests/TestStructures/SkillMaster.cs deleted file mode 100644 index 622132e..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/SkillMaster.cs +++ /dev/null @@ -1,31 +0,0 @@ -using MessagePack; - -namespace MasterMemory.Tests -{ - [MemoryTable("skillmaster"), MessagePackObject(true)] - public class SkillMaster - { - [PrimaryKey] - public int SkillId { get; set; } - [PrimaryKey] - public int SkillLevel { get; set; } - public int AttackPower { get; set; } - public string SkillName { get; set; } - public string Description { get; set; } - - public SkillMaster() - { - - } - - public SkillMaster(int SkillId, int SkillLevel, int AttackPower, string SkillName, string Description) - { - this.SkillId = SkillId; - this.SkillLevel = SkillLevel; - this.AttackPower = AttackPower; - this.SkillName = SkillName; - this.Description = Description; - } - - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/SkillMaster.cs.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures/SkillMaster.cs.meta deleted file mode 100644 index 8670b5a..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/SkillMaster.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f35d9f219aaf12b4aac66cfe87404913 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/TestMaster.cs b/src/MasterMemory.Unity/Assets/Tests/TestStructures/TestMaster.cs deleted file mode 100644 index 586d673..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/TestMaster.cs +++ /dev/null @@ -1,22 +0,0 @@ -using MessagePack; -using System; -using System.Collections.Generic; -using System.Text; - -namespace MasterMemory.Tests.TestStructures -{ - [MessagePackObject(true)] - [MemoryTable(nameof(TestMaster))] - public class TestMaster - { - [PrimaryKey, NonUnique] - public int TestID { get; set; } - public int Value { get; set; } - - public TestMaster(int TestID, int Value) - { - this.TestID = TestID; - this.Value = Value; - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/TestMaster.cs.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures/TestMaster.cs.meta deleted file mode 100644 index 8129d73..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/TestMaster.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 00c2ccf15d1ffba4da42cb7210d9c065 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/UserLevel.cs b/src/MasterMemory.Unity/Assets/Tests/TestStructures/UserLevel.cs deleted file mode 100644 index 5fb6bcc..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/UserLevel.cs +++ /dev/null @@ -1,25 +0,0 @@ -using MessagePack; - -namespace MasterMemory.Tests -{ - [MemoryTable("UserLevel"), MessagePackObject(true)] - public class UserLevel - { - [PrimaryKey] - public int Level { get; set; } - [SecondaryKey(0)] - public int Exp { get; set; } - - public UserLevel() - { - - } - - public UserLevel(int Level, int Exp) - { - this.Level = Level; - this.Exp = Exp; - } - - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/TestStructures/UserLevel.cs.meta b/src/MasterMemory.Unity/Assets/Tests/TestStructures/UserLevel.cs.meta deleted file mode 100644 index 96124f8..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/TestStructures/UserLevel.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f63856f6d3ff197418afd162890df00e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/ValidatorTest.cs b/src/MasterMemory.Unity/Assets/Tests/ValidatorTest.cs deleted file mode 100644 index a9973ae..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/ValidatorTest.cs +++ /dev/null @@ -1,296 +0,0 @@ -using MasterMemory.Tests.TestStructures; -using FluentAssertions; -using MessagePack; -using System; -using System.Collections.Generic; -using System.Text; -using Xunit; -using System.Linq; - -namespace MasterMemory.Tests -{ - public class ValidatorTest - { - readonly Xunit.Abstractions.ITestOutputHelper output; - -#if UNITY_2018_3_OR_NEWER - public ValidatorTest() - { - this.output = new Xunit.Abstractions.DebugLogTestOutputHelper(); - MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(MessagePackResolver.Instance); - } -#else - public ValidatorTest(Xunit.Abstractions.ITestOutputHelper output) - { - this.output = output; - MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(MessagePackResolver.Instance); - } -#endif - - MemoryDatabase CreateDatabase(Fail[] data1) - { - - var bin = new DatabaseBuilder() - .Append(data1) - .Build(); - - return new MemoryDatabase(bin, internString: false); - } - - MemoryDatabase CreateDatabase(SingleMaster[] data1) - { - - var bin = new DatabaseBuilder() - .Append(data1) - .Build(); - - return new MemoryDatabase(bin, internString: false); - } - - MemoryDatabase CreateDatabase(SequentialCheckMaster[] data1) - { - - var bin = new DatabaseBuilder() - .Append(data1) - .Build(); - - return new MemoryDatabase(bin, internString: false); - } - - MemoryDatabase CreateDatabase(QuestMaster[] data1, ItemMaster[] data2) - { - - var bin = new DatabaseBuilder() - .Append(data1) - .Append(data2) - .Build(); - - return new MemoryDatabase(bin, internString: false); - } - - MemoryDatabase CreateDatabase(QuestMasterEmptyValidate[] data1, ItemMasterEmptyValidate[] data2) - { - - var bin = new DatabaseBuilder() - .Append(data1) - .Append(data2) - .Build(); - - return new MemoryDatabase(bin, internString: false); - } - - [Fact] - public void Empty() - { - var validateResult = CreateDatabase(new QuestMaster[] - { - }, new ItemMaster[] - { - }).Validate(); - - validateResult.IsValidationFailed.Should().BeFalse(); - validateResult.FailedResults.Count.Should().Be(0); - } - - [Fact] - public void PKUnique() - { - var validateResult = CreateDatabase(new QuestMasterEmptyValidate[] - { - new QuestMasterEmptyValidate { QuestId = 1 }, - new QuestMasterEmptyValidate { QuestId = 2 }, - new QuestMasterEmptyValidate { QuestId = 1 }, - new QuestMasterEmptyValidate { QuestId = 4 }, - new QuestMasterEmptyValidate { QuestId = 4 }, - }, new ItemMasterEmptyValidate[] - { - new ItemMasterEmptyValidate { ItemId = 1 }, - new ItemMasterEmptyValidate { ItemId = 2 }, - new ItemMasterEmptyValidate { ItemId = 2 }, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - - validateResult.IsValidationFailed.Should().BeTrue(); - validateResult.FailedResults.Count.Should().Be(3); // Q:1,4 + I:2 - validateResult.FailedResults[0].Message.Should().Be("Unique failed: QuestId, value = 1"); - validateResult.FailedResults[1].Message.Should().Be("Unique failed: QuestId, value = 4"); - validateResult.FailedResults[2].Message.Should().Be("Unique failed: ItemId, value = 2"); - } - - // test IValidator - - /* - public interface IValidator - { - ValidatableSet GetTableSet(); - ReferenceSet GetReferenceSet(); - void Validate(Expression> predicate); - void Validate(Func predicate, string message); - void ValidateAction(Expression> predicate); - void ValidateAction(Func predicate, string message); - void Fail(string message); - bool CallOnce(); - } - - ReferenceSet.Exists - ValidatableSet.Unique - ValidatableSet.Sequential - */ - - [Fact] - public void Exists() - { - var validateResult = CreateDatabase(new QuestMaster[] - { - new QuestMaster { QuestId = 1, RewardItemId = 1, Name = "foo" }, - new QuestMaster { QuestId = 2, RewardItemId = 3, Name = "bar" }, - new QuestMaster { QuestId = 3, RewardItemId = 2, Name = "baz" }, - new QuestMaster { QuestId = 4, RewardItemId = 5, Name = "tako"}, - new QuestMaster { QuestId = 5, RewardItemId = 4, Name = "nano"}, - }, new ItemMaster[] - { - new ItemMaster { ItemId = 1 }, - new ItemMaster { ItemId = 2 }, - new ItemMaster { ItemId = 3 }, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeTrue(); - - validateResult.FailedResults[0].Message.Should().Be("Exists failed: QuestMaster.RewardItemId -> ItemMaster.ItemId, value = 5, PK(QuestId) = 4"); - validateResult.FailedResults[1].Message.Should().Be("Exists failed: QuestMaster.RewardItemId -> ItemMaster.ItemId, value = 4, PK(QuestId) = 5"); - } - - [Fact] - public void Unique() - { - var validateResult = CreateDatabase(new QuestMaster[] - { - new QuestMaster { QuestId = 1, Name = "foo" }, - new QuestMaster { QuestId = 2, Name = "bar" }, - new QuestMaster { QuestId = 3, Name = "bar" }, - new QuestMaster { QuestId = 4, Name = "tako" }, - new QuestMaster { QuestId = 5, Name = "foo" }, - }, new ItemMaster[] - { - new ItemMaster { ItemId = 0 } - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeTrue(); - - validateResult.FailedResults[0].Message.Should().Be("Unique failed: .Name, value = bar, PK(QuestId) = 3"); - validateResult.FailedResults[1].Message.Should().Be("Unique failed: .Name, value = foo, PK(QuestId) = 5"); - } - - [Fact] - public void Sequential() - { - { - var validateResult = CreateDatabase(new SequentialCheckMaster[] - { - new SequentialCheckMaster { Id = 1, Cost = 10 }, - new SequentialCheckMaster { Id = 2, Cost = 11 }, - new SequentialCheckMaster { Id = 3, Cost = 11 }, - new SequentialCheckMaster { Id = 4, Cost = 12 }, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeFalse(); - } - { - var validateResult = CreateDatabase(new SequentialCheckMaster[] - { - new SequentialCheckMaster { Id = 1, Cost = 10 }, - new SequentialCheckMaster { Id = 2, Cost = 11 }, - new SequentialCheckMaster { Id = 3, Cost = 11 }, - new SequentialCheckMaster { Id = 5, Cost = 13 }, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeTrue(); - - validateResult.FailedResults[0].Message.Should().Be("Sequential failed: .Id, value = (3, 5), PK(Id) = 5"); - validateResult.FailedResults[1].Message.Should().Be("Sequential failed: .Cost, value = (11, 13), PK(Id) = 5"); - } - } - - [Fact] - public void CallOnce() - { - _ = CreateDatabase(new SingleMaster[] - { - new SingleMaster { Id = 1}, - new SingleMaster { Id = 2}, - new SingleMaster { Id = 3}, - new SingleMaster { Id = 4}, - }).Validate(); - - - SingleMaster.CalledValidateCount.Should().Be(4); - SingleMaster.CalledOnceCount.Should().Be(1); - } - - [Fact] - public void Validate() - { - var validateResult = CreateDatabase(new QuestMaster[] - { - new QuestMaster { QuestId = 1, RewardItemId = 1, Name = "foo", Cost = -1 }, - new QuestMaster { QuestId = 2, RewardItemId = 3, Name = "bar", Cost = 99 }, - new QuestMaster { QuestId = 3, RewardItemId = 2, Name = "baz", Cost = 100 }, - new QuestMaster { QuestId = 4, RewardItemId = 3, Name = "tao", Cost = 101 }, - new QuestMaster { QuestId = 5, RewardItemId = 3, Name = "nao", Cost = 33 }, - }, new ItemMaster[] - { - new ItemMaster { ItemId = 1 }, - new ItemMaster { ItemId = 2 }, - new ItemMaster { ItemId = 3 }, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeTrue(); - - validateResult.FailedResults[0].Message.Should().Be("Validate failed: >= 0!!!, PK(QuestId) = 1"); - validateResult.FailedResults[1].Message.Should().Be("Validate failed: (this.Cost <= 100), Cost = 101, PK(QuestId) = 4"); - } - - [Fact] - public void ValidateAction() - { - var validateResult = CreateDatabase(new QuestMaster[] - { - new QuestMaster { QuestId = 1, RewardItemId = 1, Name = "foo", Cost = -100 }, - new QuestMaster { QuestId = 2, RewardItemId = 3, Name = "bar", Cost = 99 }, - new QuestMaster { QuestId = 3, RewardItemId = 2, Name = "baz", Cost = 100 }, - new QuestMaster { QuestId = 4, RewardItemId = 3, Name = "tao", Cost = 1001 }, - new QuestMaster { QuestId = 5, RewardItemId = 3, Name = "nao", Cost = 33 }, - }, new ItemMaster[] - { - new ItemMaster { ItemId = 1 }, - new ItemMaster { ItemId = 2 }, - new ItemMaster { ItemId = 3 }, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeTrue(); - - var results = validateResult.FailedResults.Select(x => x.Message).Where(x => x.Contains("ValidateAction faile")).ToArray(); - - results[0].Should().Be("ValidateAction failed: >= -90!!!, PK(QuestId) = 1"); - results[1].Should().Be("ValidateAction failed: (value(MasterMemory.Tests.TestStructures.QuestMaster).Cost <= 1000), PK(QuestId) = 4"); - } - - [Fact] - public void Fail() - { - var validateResult = CreateDatabase(new Fail[] - { - new Fail { Id = 1}, - new Fail { Id = 2}, - new Fail { Id = 3}, - }).Validate(); - output.WriteLine(validateResult.FormatFailedResults()); - validateResult.IsValidationFailed.Should().BeTrue(); - - var msg = validateResult.FailedResults.Select(x => x.Message).ToArray(); - msg[0].Should().Be("Failed Id:1, PK(Id) = 1"); - msg[1].Should().Be("Failed Id:2, PK(Id) = 2"); - msg[2].Should().Be("Failed Id:3, PK(Id) = 3"); - } - } -} diff --git a/src/MasterMemory.Unity/Assets/Tests/ValidatorTest.cs.meta b/src/MasterMemory.Unity/Assets/Tests/ValidatorTest.cs.meta deleted file mode 100644 index fdb6ceb..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/ValidatorTest.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b712d28e4491b89439499d8349cf1ad5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/Tests/_Shims.cs b/src/MasterMemory.Unity/Assets/Tests/_Shims.cs deleted file mode 100644 index a5e0ddd..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/_Shims.cs +++ /dev/null @@ -1,187 +0,0 @@ -using NUnit.Framework; -using System.Linq; -using System.Collections.Generic; -using System; - -namespace Xunit -{ - public class FactAttribute : TestAttribute - { - - } - - public static class Assert - { - public static void Throws(Action action) where T : Exception - { - NUnit.Framework.Assert.Throws(new TestDelegate(action)); - } - - public static void Throws(Func action) where T : Exception - { - NUnit.Framework.Assert.Throws(() => action()); - } - } -} - -namespace Xunit.Abstractions -{ - public interface ITestOutputHelper - { - void WriteLine(String message); - void WriteLine(String format, params Object[] args); - } - - public class DebugLogTestOutputHelper : ITestOutputHelper - { - public void WriteLine(string message) - { - UnityEngine.Debug.Log(message); - } - - public void WriteLine(string format, params object[] args) - { - UnityEngine.Debug.Log(string.Format(format, args)); - } - } -} - - -namespace FluentAssertions -{ - public static class FluentAssertionsExtensions - { - public static Int Should(this int value) - { - return new Int(value); - } - public static Bool Should(this bool value) - { - return new Bool(value); - } - - public static Generic Should(this T value) - { - return new Generic(value); - } - - public static Collection Should(this T[] value) - { - return new Collection(value); - } - - public static Collection Should(this IEnumerable value) - { - return new Collection(value); - } - - public static Collection Should(this IOrderedEnumerable value) - { - return new Collection(value); - } - - public class Collection - { - readonly IEnumerable actual; - - public Collection(IEnumerable actual) - { - this.actual = actual; - } - - public void BeEquivalentTo(T[] expected) - { - Assert.True(actual.SequenceEqual(expected)); - } - - public void BeEquivalentTo(IEnumerable expected) - { - Assert.True(actual.SequenceEqual(expected)); - } - } - - public class Generic - { - readonly T actual; - - public Generic(T value) - { - actual = value; - } - - public void Be(T expected) - { - Assert.AreEqual(expected, actual); - } - - public void NotBe(T expected) - { - Assert.AreNotEqual(expected, actual); - } - - public void BeNull() - { - Assert.IsNull(actual); - } - - public void NotBeNull() - { - Assert.IsNotNull(actual); - } - } - - public class Int - { - readonly int actual; - - public Int(int value) - { - actual = value; - } - - public void Be(int expected) - { - Assert.AreEqual(expected, actual); - } - - public void NotBe(int expected) - { - Assert.AreNotEqual(expected, actual); - } - - public void BeCloseTo(int expected, int delta) - { - if (expected - delta <= actual && actual <= expected + delta) - { - // OK. - } - else - { - Assert.Fail($"Fail BeCloseTo, actual {actual} but expected:{expected} +- {delta}"); - } - } - } - - - - public class Bool - { - bool actual; - - public Bool(bool actual) - { - this.actual = actual; - } - - public void BeTrue() - { - Assert.AreEqual(true, actual); - } - - public void BeFalse() - { - Assert.AreEqual(false, actual); - } - } - } -} \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Tests/_Shims.cs.meta b/src/MasterMemory.Unity/Assets/Tests/_Shims.cs.meta deleted file mode 100644 index 6040309..0000000 --- a/src/MasterMemory.Unity/Assets/Tests/_Shims.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: fcbc5fef2faa47242b1f85f3d36566f4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/src/MasterMemory.Unity/Assets/packages.config b/src/MasterMemory.Unity/Assets/packages.config new file mode 100644 index 0000000..bae8f60 --- /dev/null +++ b/src/MasterMemory.Unity/Assets/packages.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/MasterMemory.Unity/Assets/Plugins/System.Memory.dll.meta b/src/MasterMemory.Unity/Assets/packages.config.meta similarity index 57% rename from src/MasterMemory.Unity/Assets/Plugins/System.Memory.dll.meta rename to src/MasterMemory.Unity/Assets/packages.config.meta index 3611bd4..5f4b783 100644 --- a/src/MasterMemory.Unity/Assets/Plugins/System.Memory.dll.meta +++ b/src/MasterMemory.Unity/Assets/packages.config.meta @@ -1,5 +1,7 @@ fileFormatVersion: 2 -guid: 4b54c65c745fd3f8b9b5d1ee2b691920 +guid: 44858e3667fc6e44c8fc19fd02574910 +labels: +- NuGetForUnity PluginImporter: externalObjects: {} serializedVersion: 2 @@ -16,18 +18,6 @@ PluginImporter: 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/src/MasterMemory.Unity/Packages/manifest.json b/src/MasterMemory.Unity/Packages/manifest.json index 3fd89e4..a56df11 100644 --- a/src/MasterMemory.Unity/Packages/manifest.json +++ b/src/MasterMemory.Unity/Packages/manifest.json @@ -1,6 +1,8 @@ { "dependencies": { "com.cysharp.runtimeunittesttoolkit": "https://github.com/Cysharp/RuntimeUnitTestToolkit.git?path=RuntimeUnitTestToolkit/Assets/RuntimeUnitTestToolkit#2.6.0", + "com.github-glitchenzo.nugetforunity": "https://github.com/GlitchEnzo/NuGetForUnity.git?path=/src/NuGetForUnity", + "com.github.mastermemory.internal": "file:C:/Users/S04451/Documents/GitHub/MasterMemory/src/MasterMemory/bin/Debug/netstandard2.0", "com.unity.ide.rider": "3.0.31", "com.unity.ide.visualstudio": "2.0.22", "com.unity.ide.vscode": "1.2.5", diff --git a/src/MasterMemory.Unity/Packages/packages-lock.json b/src/MasterMemory.Unity/Packages/packages-lock.json index 8dd51f5..f6feba0 100644 --- a/src/MasterMemory.Unity/Packages/packages-lock.json +++ b/src/MasterMemory.Unity/Packages/packages-lock.json @@ -7,6 +7,19 @@ "dependencies": {}, "hash": "4e3dbfaa9c40b5cfdcb71a1d4e8bca0d45ca1055" }, + "com.github-glitchenzo.nugetforunity": { + "version": "https://github.com/GlitchEnzo/NuGetForUnity.git?path=/src/NuGetForUnity", + "depth": 0, + "source": "git", + "dependencies": {}, + "hash": "7c80e98d3b56ecbcf854a9336458b6b0dedf1b8f" + }, + "com.github.mastermemory.internal": { + "version": "file:C:/Users/S04451/Documents/GitHub/MasterMemory/src/MasterMemory/bin/Debug/netstandard2.0", + "depth": 0, + "source": "local", + "dependencies": {} + }, "com.unity.ext.nunit": { "version": "1.0.6", "depth": 1, diff --git a/src/MasterMemory.Unity/ProjectSettings/ProjectSettings.asset b/src/MasterMemory.Unity/ProjectSettings/ProjectSettings.asset index 8d08472..7318aed 100644 --- a/src/MasterMemory.Unity/ProjectSettings/ProjectSettings.asset +++ b/src/MasterMemory.Unity/ProjectSettings/ProjectSettings.asset @@ -76,7 +76,6 @@ PlayerSettings: androidMinimumWindowWidth: 400 androidMinimumWindowHeight: 300 androidFullscreenMode: 1 - androidAutoRotationBehavior: 1 defaultIsNativeResolution: 1 macRetinaSupport: 1 runInBackground: 1 @@ -137,8 +136,6 @@ PlayerSettings: vulkanEnableLateAcquireNextImage: 0 vulkanEnableCommandBufferRecycling: 1 loadStoreDebugModeEnabled: 0 - visionOSBundleVersion: 1.0 - tvOSBundleVersion: 1.0 bundleVersion: 0.1 preloadedAssets: [] metroInputSource: 0 @@ -161,7 +158,7 @@ PlayerSettings: androidSupportedAspectRatio: 1 androidMaxAspectRatio: 2.1 applicationIdentifier: - Standalone: com.Company.ProductName + Standalone: com.DefaultCompany.MasterMemory buildNumber: Standalone: 0 VisionOS: 0 @@ -233,7 +230,6 @@ PlayerSettings: iOSMetalForceHardShadows: 0 metalEditorSupport: 1 metalAPIValidation: 1 - metalCompileShaderBinary: 0 iOSRenderExtraFrameOnPause: 0 iosCopyPluginsCodeInsteadOfSymlink: 0 appleDeveloperTeamID: @@ -374,6 +370,7 @@ PlayerSettings: switchScreenResolutionBehavior: 2 switchUseCPUProfiler: 0 switchEnableFileSystemTrace: 0 + switchUseGOLDLinker: 0 switchLTOSetting: 0 switchApplicationID: 0x01004b9000490000 switchNSODependencies: @@ -667,7 +664,6 @@ PlayerSettings: metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628, a: 1} metroSplashScreenUseBackgroundColor: 0 - syncCapabilities: 0 platformCapabilities: {} metroTargetDeviceFamilies: {} metroFTAName: diff --git a/src/MasterMemory.Unity/ProjectSettings/ProjectVersion.txt b/src/MasterMemory.Unity/ProjectSettings/ProjectVersion.txt index 32f4211..e4eac15 100644 --- a/src/MasterMemory.Unity/ProjectSettings/ProjectVersion.txt +++ b/src/MasterMemory.Unity/ProjectSettings/ProjectVersion.txt @@ -1,2 +1,2 @@ -m_EditorVersion: 2022.3.39f1 -m_EditorVersionWithRevision: 2022.3.39f1 (4e1b0f82c39a) +m_EditorVersion: 2022.3.12f1 +m_EditorVersionWithRevision: 2022.3.12f1 (4fe6e059c7ef) diff --git a/src/MasterMemory/DatabaseBuilderBase.cs b/src/MasterMemory/DatabaseBuilderBase.cs index a1b1429..9784106 100644 --- a/src/MasterMemory/DatabaseBuilderBase.cs +++ b/src/MasterMemory/DatabaseBuilderBase.cs @@ -14,9 +14,9 @@ public abstract class DatabaseBuilderBase // TableName, (Offset, Count) readonly Dictionary header = new Dictionary(); - readonly MessagePackSerializerOptions options; + readonly MessagePackSerializerOptions? options; - public DatabaseBuilderBase(MessagePackSerializerOptions options) + public DatabaseBuilderBase(MessagePackSerializerOptions? options) { // options keep null to lazily use default options if (options != null) @@ -25,7 +25,7 @@ public DatabaseBuilderBase(MessagePackSerializerOptions options) } } - public DatabaseBuilderBase(IFormatterResolver resolver) + public DatabaseBuilderBase(IFormatterResolver? resolver) { if (resolver != null) { @@ -79,8 +79,8 @@ static TElement[] FastSort(IEnumerable datasource, Fun } else { - var array = new ExpandableArray(null); - var sortSource = new ExpandableArray(null); + var array = new ExpandableArray(null!); + var sortSource = new ExpandableArray(null!); foreach (var item in datasource) { array.Add(item); diff --git a/src/MasterMemory/Internal/HeaderFormatterResolver.cs b/src/MasterMemory/Internal/HeaderFormatterResolver.cs index 4b4f3b7..ace38fd 100644 --- a/src/MasterMemory/Internal/HeaderFormatterResolver.cs +++ b/src/MasterMemory/Internal/HeaderFormatterResolver.cs @@ -11,7 +11,7 @@ internal class HeaderFormatterResolver : IFormatterResolver public static readonly IFormatterResolver Instance = new HeaderFormatterResolver(); public static readonly MessagePackSerializerOptions StandardOptions = MessagePackSerializerOptions.Standard.WithResolver(Instance); - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { if (typeof(T) == typeof(Dictionary)) { diff --git a/src/MasterMemory/Internal/InternStringResolver.cs b/src/MasterMemory/Internal/InternStringResolver.cs index d3adef8..e4906e8 100644 --- a/src/MasterMemory/Internal/InternStringResolver.cs +++ b/src/MasterMemory/Internal/InternStringResolver.cs @@ -4,7 +4,8 @@ namespace MasterMemory.Internal { - internal class InternStringResolver : IFormatterResolver, IMessagePackFormatter +#pragma warning disable MsgPack013 // Inaccessible formatter + internal class InternStringResolver : IFormatterResolver, IMessagePackFormatter { readonly IFormatterResolver innerResolver; @@ -13,7 +14,7 @@ public InternStringResolver(IFormatterResolver innerResolver) this.innerResolver = innerResolver; } - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { if (typeof(T) == typeof(string)) { @@ -23,7 +24,7 @@ public IMessagePackFormatter GetFormatter() return innerResolver.GetFormatter(); } - string IMessagePackFormatter.Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + string? IMessagePackFormatter.Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { var str = reader.ReadString(); if (str == null) @@ -34,7 +35,7 @@ string IMessagePackFormatter.Deserialize(ref MessagePackReader reader, M return string.Intern(str); } - void IMessagePackFormatter.Serialize(ref MessagePackWriter writer, string value, MessagePackSerializerOptions options) + void IMessagePackFormatter.Serialize(ref MessagePackWriter writer, string? value, MessagePackSerializerOptions options) { throw new NotImplementedException(); } diff --git a/src/MasterMemory/MasterMemory.csproj b/src/MasterMemory/MasterMemory.csproj index 0a58b06..d939d02 100644 --- a/src/MasterMemory/MasterMemory.csproj +++ b/src/MasterMemory/MasterMemory.csproj @@ -1,68 +1,69 @@  - - netstandard2.0 - MasterMemory - MasterMemory + + netstandard2.0 + MasterMemory + MasterMemory + 13 + enable + Library + False + Cysharp + true + 1701;1702;1705;1591 - Library - False - Cysharp - true - 1701;1702;1705;1591 + + MasterMemory + $(Version) + Cysharp + Cysharp + Embedded Typed Readonly In-Memory Document Database for .NET Core and Unity. + https://github.com/Cysharp/MasterMemory + $(PackageProjectUrl) + git + database, embedded, inmemory, unity + true - - MasterMemory - $(Version) - Cysharp - Cysharp - Embedded Typed Readonly In-Memory Document Database for .NET Core and Unity. - https://github.com/Cysharp/MasterMemory - $(PackageProjectUrl) - git - database, embedded, inmemory, unity - true - + + $(TargetsForTfmSpecificContentInPackage);PackBuildOutputs + - - - + + + + + + + - - - + + + - - - TextTemplatingFileGenerator - ValidatableSet.Sequential.cs - - - - - - - - True - True - ValidatableSet.Sequential.tt - - + + - - - $(ProjectDir)..\MasterMemory.Unity\Assets\Scripts\MasterMemory\ - $(ProjectDir)..\MasterMemory.Unity\Assets\Tests\ - - - - - - - - - - - + + + + + + + TextTemplatingFileGenerator + ValidatableSet.Sequential.cs + + + + + + + + True + True + ValidatableSet.Sequential.tt + + diff --git a/src/MasterMemory/MemoryDatabaseBase.cs b/src/MasterMemory/MemoryDatabaseBase.cs index d1d873d..1b1bb17 100644 --- a/src/MasterMemory/MemoryDatabaseBase.cs +++ b/src/MasterMemory/MemoryDatabaseBase.cs @@ -17,7 +17,7 @@ protected MemoryDatabaseBase() } - public MemoryDatabaseBase(byte[] databaseBinary, bool internString = true, IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) + public MemoryDatabaseBase(byte[] databaseBinary, bool internString = true, IFormatterResolver? formatterResolver = null, int maxDegreeOfParallelism = 1) { var reader = new MessagePackReader(databaseBinary); var formatter = new DictionaryFormatter(); @@ -33,7 +33,7 @@ public MemoryDatabaseBase(byte[] databaseBinary, bool internString = true, IForm maxDegreeOfParallelism = 1; } - Init(header, databaseBinary.AsMemory((int)reader.Consumed), MessagePackSerializer.DefaultOptions.WithResolver(resolver).WithCompression(MessagePackCompression.Lz4Block), maxDegreeOfParallelism); + Init(header!, databaseBinary.AsMemory((int)reader.Consumed), MessagePackSerializer.DefaultOptions.WithResolver(resolver).WithCompression(MessagePackCompression.Lz4Block), maxDegreeOfParallelism); } protected static TView ExtractTableData(Dictionary header, ReadOnlyMemory databaseBinary, MessagePackSerializerOptions options, Func createView) @@ -86,9 +86,9 @@ public class TableInfo { public string TableName { get; } public int Size { get; } - byte[] binaryData; + byte[]? binaryData; - public TableInfo(string tableName, int size, byte[] rawBinary, int offset) + public TableInfo(string tableName, int size, byte[]? rawBinary, int offset) { TableName = tableName; Size = size; diff --git a/src/MasterMemory/Meta/Meta.cs b/src/MasterMemory/Meta/Meta.cs index da1e23f..f341852 100644 --- a/src/MasterMemory/Meta/Meta.cs +++ b/src/MasterMemory/Meta/Meta.cs @@ -25,7 +25,7 @@ public IEnumerable GetTableInfos() } } - public MetaTable GetTableInfo(string tableName) + public MetaTable? GetTableInfo(string tableName) { return tableInfos.TryGetValue(tableName, out var table) ? table @@ -64,9 +64,9 @@ public class MetaProperty public string NameLowerCamel => ToCamelCase(PropertyInfo.Name); public string NameSnakeCase => ToSnakeCase(PropertyInfo.Name); - public MetaProperty(PropertyInfo propertyInfo) + public MetaProperty(PropertyInfo? propertyInfo) { - PropertyInfo = propertyInfo; + PropertyInfo = propertyInfo!; } public override string ToString() diff --git a/src/MasterMemory/RangeView.cs b/src/MasterMemory/RangeView.cs index 1a9be6f..e59e38a 100644 --- a/src/MasterMemory/RangeView.cs +++ b/src/MasterMemory/RangeView.cs @@ -6,9 +6,9 @@ namespace MasterMemory { public readonly struct RangeView : IEnumerable, IReadOnlyList, IList { - public static RangeView Empty => new RangeView( null, -1, -1, false ); + public static RangeView Empty => new RangeView(null, -1, -1, false); - readonly T[] orderedData; + readonly T[]? orderedData; readonly int left; readonly int right; readonly bool ascendant; @@ -35,18 +35,18 @@ public T this[int index] if (ascendant) { - return orderedData[left + index]; + return orderedData![left + index]; } else { - return orderedData[right - index]; + return orderedData![right - index]; } } } - public RangeView(T[] orderedData, int left, int right, bool ascendant) + public RangeView(T[]? orderedData, int left, int right, bool ascendant) { - this.hasValue = (orderedData != null ) && (orderedData.Length != 0) && (left <= right); // same index is length = 1 this.orderedData = orderedData; + this.hasValue = (orderedData != null) && (orderedData.Length != 0) && (left <= right); // same index is length = 1 this.orderedData = orderedData; this.orderedData = orderedData; this.left = left; this.right = right; diff --git a/src/MasterMemory/TableBase.cs b/src/MasterMemory/TableBase.cs index 85e114d..ecbd896 100644 --- a/src/MasterMemory/TableBase.cs +++ b/src/MasterMemory/TableBase.cs @@ -31,7 +31,7 @@ static protected void ValidateUniqueCore(TElement[] indexArray, Func(TElement[] indexArray, Func(TElement[] indexArray, Func(TElement[] indexArray, Func keySelector, IComparer comparer, TKey key, bool selectLower) + static protected TElement? FindUniqueClosestCore(TElement[] indexArray, Func keySelector, IComparer comparer, TKey key, bool selectLower) { var index = BinarySearch.FindClosest(indexArray, 0, indexArray.Length, key, keySelector, comparer, selectLower); return (index != -1) ? indexArray[index] : default(TElement); diff --git a/src/MasterMemory/Validation/ExpressionParameterNameModifier.cs b/src/MasterMemory/Validation/ExpressionParameterNameModifier.cs index c996c74..76b04a9 100644 --- a/src/MasterMemory/Validation/ExpressionParameterNameModifier.cs +++ b/src/MasterMemory/Validation/ExpressionParameterNameModifier.cs @@ -31,21 +31,21 @@ public static string ToThisBodyString(this Expression> predicat { var newNameParameter = Expression.Parameter(typeof(T), "this"); var newExpression = new ExpressionParameterNameModifier(predicate.Parameters[0], newNameParameter).Visit(predicate); - return (newExpression as Expression>).Body.ToString(); + return (newExpression as Expression>)!.Body.ToString(); } public static string ToSpaceBodyString(this Expression> selector) { var newNameParameter = Expression.Parameter(typeof(T), " "); var newExpression = new ExpressionParameterNameModifier(selector.Parameters[0], newNameParameter).Visit(selector); - return (newExpression as Expression>).Body.ToString(); + return (newExpression as Expression>)!.Body.ToString(); } public static string ToNameBodyString(this Expression> selector, string newName) { var newNameParameter = Expression.Parameter(typeof(T), newName); var newExpression = new ExpressionParameterNameModifier(selector.Parameters[0], newNameParameter).Visit(selector); - return (newExpression as Expression>).Body.ToString(); + return (newExpression as Expression>)!.Body.ToString(); } } } diff --git a/src/MasterMemory/Validation/ReferenceSet.cs b/src/MasterMemory/Validation/ReferenceSet.cs index 12d3ceb..963c8c1 100644 --- a/src/MasterMemory/Validation/ReferenceSet.cs +++ b/src/MasterMemory/Validation/ReferenceSet.cs @@ -46,7 +46,7 @@ public void Exists(Expression> elementSelec // not found, assert. var from = elementSelector.ToNameBodyString(typeof(TElement).Name); var to = referenceElementSelector.ToNameBodyString(typeof(TReference).Name); - resultSet.AddFail(typeof(TElement), "Exists failed: " + from + " -> " + to + ", value = " + compareBase + ", " + BuildPkMessage(), item); + resultSet.AddFail(typeof(TElement), "Exists failed: " + from + " -> " + to + ", value = " + compareBase + ", " + BuildPkMessage(), item!); } string BuildPkMessage() diff --git a/src/MasterMemory/Validation/ValidatableSet.Sequential.cs b/src/MasterMemory/Validation/ValidatableSet.Sequential.cs index 2b8f498..148d43c 100644 --- a/src/MasterMemory/Validation/ValidatableSet.Sequential.cs +++ b/src/MasterMemory/Validation/ValidatableSet.Sequential.cs @@ -34,7 +34,7 @@ void SequentialCore(Func selector, Func message, bool d if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -68,7 +68,7 @@ void SequentialCore(Func selector, Func message, bool d if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -102,7 +102,7 @@ void SequentialCore(Func selector, Func message, bool d if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -136,7 +136,7 @@ void SequentialCore(Func selector, Func message, bool d if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -170,7 +170,7 @@ void SequentialCore(Func selector, Func message, bool di if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -204,7 +204,7 @@ void SequentialCore(Func selector, Func message, bool if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -238,7 +238,7 @@ void SequentialCore(Func selector, Func message, bool if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; @@ -272,7 +272,7 @@ void SequentialCore(Func selector, Func message, bool if ((prev + 1) != curr) { - resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]); + resultSet.AddFail(typeof(TElement), "Sequential failed:" + message() + ", value = " + (prev, curr) + ", " + BuildPkMessage(data[i]), data[i]!); } prev = curr; diff --git a/src/MasterMemory/Validation/ValidatableSet.cs b/src/MasterMemory/Validation/ValidatableSet.cs index 5ebe6e3..49a016b 100644 --- a/src/MasterMemory/Validation/ValidatableSet.cs +++ b/src/MasterMemory/Validation/ValidatableSet.cs @@ -37,7 +37,7 @@ public void Unique(Expression> selector, IE var v = f(item); if (!set.Add(v)) { - resultSet.AddFail(typeof(TElement), "Unique failed:" + selector.ToSpaceBodyString() + ", value = " + v + ", " + BuildPkMessage(item), item); + resultSet.AddFail(typeof(TElement), "Unique failed:" + selector.ToSpaceBodyString() + ", value = " + v + ", " + BuildPkMessage(item), item!); } } } @@ -55,7 +55,7 @@ public void Unique(Func selector, IEqualityCompa var v = selector(item); if (!set.Add(v)) { - resultSet.AddFail(typeof(TElement), "Unique failed: " + message + ", value = " + v + ", " + BuildPkMessage(item), item); + resultSet.AddFail(typeof(TElement), "Unique failed: " + message + ", value = " + v + ", " + BuildPkMessage(item), item!); } } } diff --git a/src/MasterMemory/Validation/ValidationDatabase.cs b/src/MasterMemory/Validation/ValidationDatabase.cs index e6005c0..e352ce4 100644 --- a/src/MasterMemory/Validation/ValidationDatabase.cs +++ b/src/MasterMemory/Validation/ValidationDatabase.cs @@ -30,7 +30,7 @@ internal IReadOnlyList GetTable() throw new InvalidOperationException("Can not create validator in " + typeof(T).FullName); } var data = table as IReadOnlyList; - return data; + return data!; } } } diff --git a/src/MasterMemory/Validation/Validator.cs b/src/MasterMemory/Validation/Validator.cs index 4480741..0391f42 100644 --- a/src/MasterMemory/Validation/Validator.cs +++ b/src/MasterMemory/Validation/Validator.cs @@ -51,7 +51,7 @@ public void Validate(Expression> predicate) { var memberValues = ExpressionDumper.DumpMemberValues(item, predicate); var message = string.Format($"{predicate.ToThisBodyString()}, {memberValues}, {BuildPkMessage()}"); - resultSet.AddFail(typeof(T), "Validate failed: " + message, item); + resultSet.AddFail(typeof(T), "Validate failed: " + message, item!); } } @@ -59,7 +59,7 @@ public void Validate(Func predicate, string message) { if (!predicate(item)) { - resultSet.AddFail(typeof(T), "Validate failed: " + message + ", " + BuildPkMessage(), item); + resultSet.AddFail(typeof(T), "Validate failed: " + message + ", " + BuildPkMessage(), item!); } } @@ -68,7 +68,7 @@ public void ValidateAction(Expression> predicate) if (!predicate.Compile(true).Invoke()) { var expr = predicate.Body.ToString(); - resultSet.AddFail(typeof(T), "ValidateAction failed: " + expr + ", " + BuildPkMessage(), item); + resultSet.AddFail(typeof(T), "ValidateAction failed: " + expr + ", " + BuildPkMessage(), item!); } } @@ -76,13 +76,13 @@ public void ValidateAction(Func predicate, string message) { if (!predicate()) { - resultSet.AddFail(typeof(T), "ValidateAction failed: " + message + ", " + BuildPkMessage(), item); + resultSet.AddFail(typeof(T), "ValidateAction failed: " + message + ", " + BuildPkMessage(), item!); } } public void Fail(string message) { - resultSet.AddFail(typeof(T), message + ", " + BuildPkMessage(), item); + resultSet.AddFail(typeof(T), message + ", " + BuildPkMessage(), item!); } string BuildPkMessage() diff --git a/src/MasterMemory/_MessagePackResolver.cs b/src/MasterMemory/_MessagePackResolver.cs new file mode 100644 index 0000000..a1b8bc4 --- /dev/null +++ b/src/MasterMemory/_MessagePackResolver.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace MasterMemory; + +[MessagePack.GeneratedMessagePackResolver] +internal partial class _MessagePackResolver +{ +} \ No newline at end of file diff --git a/src/MasterMemory/bin/Debug/netstandard2.0/package.json b/src/MasterMemory/bin/Debug/netstandard2.0/package.json new file mode 100644 index 0000000..bb6a5b5 --- /dev/null +++ b/src/MasterMemory/bin/Debug/netstandard2.0/package.json @@ -0,0 +1,12 @@ +{ + "name": "com.github.mastermemory.internal", + "displayName": "MasterMemory Internal", + "author": { "name": "MasterMemory", "url": "https://github.com/Cysharp/MasterMemory" }, + "version": "1.0.0", + "unity": "2022.3", + "description": "Internal Package of MasterMemory for development time.", + "keywords": [ "Database" ], + "license": "MIT", + "category": "Scripting", + "dependencies": {} +} diff --git a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json.meta b/src/MasterMemory/bin/Debug/netstandard2.0/package.json.meta similarity index 76% rename from src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json.meta rename to src/MasterMemory/bin/Debug/netstandard2.0/package.json.meta index 1152165..760f418 100644 --- a/src/MasterMemory.Unity/Assets/Scripts/MasterMemory/package.json.meta +++ b/src/MasterMemory/bin/Debug/netstandard2.0/package.json.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: bdab5048e61e9ab4ba1d36e83ee7ff0c +guid: b73e5f61035018248a0ae4ff5130ae2a PackageManifestImporter: externalObjects: {} userData: diff --git a/tests/MasterMemory.SourceGenerator.Tests/AssemblyAtrributeTest.cs b/tests/MasterMemory.SourceGenerator.Tests/AssemblyAtrributeTest.cs new file mode 100644 index 0000000..3ee98a6 --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/AssemblyAtrributeTest.cs @@ -0,0 +1,54 @@ +namespace MasterMemory.SourceGenerator.Tests; + +public class AssemblyAtrributeTest(ITestOutputHelper outputHelper) : TestBase(outputHelper) +{ + [Fact] + public void NoGeneratorOptions() + { + var codes = Helper.GenerateCode(""" +[MemoryTable("item")] +public class Item +{ + [PrimaryKey] + public int ItemId { get; set; } +} +"""); + + codes.TryGetValue("MasterMemory.DatabaseBuilder.g.cs", out _).Should().BeTrue(); + + var mainCode = codes["MasterMemory.ItemTable.g.cs"]; + WriteLine(mainCode); + + mainCode.Should().Contain("namespace MasterMemory.Tables"); + mainCode.Should().Contain("return ThrowKeyNotFound(key);"); + mainCode.Should().Contain("public sealed partial class ItemTable"); + } + + + [Fact] + public void FullOptions() + { + var codes = Helper.GenerateCode(""" +[assembly: MasterMemoryGeneratorOptions( + Namespace = "MyNamespace", + IsReturnNullIfKeyNotFound = true, + PrefixClassName = "FooBarBaz")] + +[MemoryTable("item")] +public class Item +{ + [PrimaryKey] + public int ItemId { get; set; } +} +"""); + + codes.TryGetValue("MasterMemory.FooBarBazDatabaseBuilder.g.cs", out _).Should().BeTrue(); + + var mainCode = codes["MasterMemory.ItemTable.g.cs"]; + WriteLine(mainCode); + + mainCode.Should().Contain("namespace MyNamespace.Tables"); + mainCode.Should().NotContain("return ThrowKeyNotFound(key);"); + mainCode.Should().Contain("public sealed partial class ItemTable"); + } +} diff --git a/tests/MasterMemory.SourceGenerator.Tests/DiagnosticsTest.cs b/tests/MasterMemory.SourceGenerator.Tests/DiagnosticsTest.cs new file mode 100644 index 0000000..a0926b7 --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/DiagnosticsTest.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MasterMemory.SourceGenerator.Tests; + +public class DiagnosticsTest(ITestOutputHelper outputHelper) : TestBase(outputHelper) +{ + [Fact] + public void RequirePrimaryKey() + { + Helper.Verify(1, """ +[MemoryTable("item")] +public class Item +{ + // [PrimaryKey] // No PrimaryKey + public int ItemId { get; set; } +} +""", "Item"); + } + + [Fact] + public void DuplicateSecondaryKey() + { + Helper.Verify(3, """ +[MemoryTable("item")] +public class Item +{ + [PrimaryKey] + public int ItemId1 { get; set; } + [SecondaryKey(0), SecondaryKey(1)] + public int ItemId2 { get; set; } +} +""", "ItemId2"); + } +} diff --git a/tests/MasterMemory.SourceGenerator.Tests/GenerateTest.cs b/tests/MasterMemory.SourceGenerator.Tests/GenerateTest.cs new file mode 100644 index 0000000..8957141 --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/GenerateTest.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xunit.Abstractions; + +namespace MasterMemory.SourceGenerator.Tests; + +public class GenerateTest(ITestOutputHelper outputHelper) : TestBase(outputHelper) +{ + [Fact] + public void GenerateClass() + { + Helper.Ok(""" +[MemoryTable("item")] +public class Item +{ + [PrimaryKey] + public int ItemId { get; set; } +} +"""); + } + + [Fact] + public void GenerateRecord() + { + Helper.Ok(""" +[MemoryTable("item")] +public record Item +{ + [PrimaryKey] + public int ItemId { get; set; } +} +"""); + } +} diff --git a/tests/MasterMemory.SourceGenerator.Tests/IncrementalGeneratorTest.cs b/tests/MasterMemory.SourceGenerator.Tests/IncrementalGeneratorTest.cs new file mode 100644 index 0000000..c990c81 --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/IncrementalGeneratorTest.cs @@ -0,0 +1,53 @@ +namespace MasterMemory.SourceGenerator.Tests; + +public class IncrementalGeneratorTest +{ + void VerifySourceOutputReasonIsCached((string Key, string Reasons)[] reasons) + { + var reason = reasons.FirstOrDefault(x => x.Key == "SourceOutput").Reasons; + reason.Should().Be("Cached"); + } + + void VerifySourceOutputReasonIsNotCached((string Key, string Reasons)[] reasons) + { + var reason = reasons.FirstOrDefault(x => x.Key == "SourceOutput").Reasons; + reason.Should().NotBe("Cached"); + } + + [Fact] + public void CheckReasons() + { + var step1 = """ +[MemoryTable("item")] +public class Item +{ + [PrimaryKey] + public int ItemId { get; set; } +} +"""; + + var step2 = """ +[MemoryTable("item")] +public class Item +{ + // add unrelated line + [PrimaryKey] + public int ItemId { get; set; } +} +"""; + + var step3 = """ +[MemoryTable("item")] +public class Item +{ + [PrimaryKey] + public int ItemId2 { get; set; } // changed name +} +"""; + + var reasons = CSharpGeneratorRunner.GetIncrementalGeneratorTrackedStepsReasons("MasterMemory.SyntaxProvider.", step1, step2, step3); + + VerifySourceOutputReasonIsCached(reasons[1]); + VerifySourceOutputReasonIsNotCached(reasons[2]); + } +} diff --git a/tests/MasterMemory.SourceGenerator.Tests/MasterMemory.SourceGenerator.Tests.csproj b/tests/MasterMemory.SourceGenerator.Tests/MasterMemory.SourceGenerator.Tests.csproj new file mode 100644 index 0000000..bb4c60d --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/MasterMemory.SourceGenerator.Tests.csproj @@ -0,0 +1,29 @@ + + + + net9.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/MasterMemory.SourceGenerator.Tests/TestBase.cs b/tests/MasterMemory.SourceGenerator.Tests/TestBase.cs new file mode 100644 index 0000000..ac87335 --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/TestBase.cs @@ -0,0 +1,11 @@ +namespace MasterMemory.SourceGenerator.Tests; + +public abstract class TestBase(ITestOutputHelper testoutputHelper) +{ + protected CodeGeneratorHelper Helper = new CodeGeneratorHelper(testoutputHelper, "MAM"); + + protected void WriteLine(string message) + { + testoutputHelper.WriteLine(message); + } +} diff --git a/tests/MasterMemory.SourceGenerator.Tests/Utility/CSharpGeneratorRunner.cs b/tests/MasterMemory.SourceGenerator.Tests/Utility/CSharpGeneratorRunner.cs new file mode 100644 index 0000000..7b40d81 --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/Utility/CSharpGeneratorRunner.cs @@ -0,0 +1,145 @@ +using MasterMemory.SourceGenerator; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Runtime.Loader; + +public static class CSharpGeneratorRunner +{ + static Compilation baseCompilation = default!; + + [ModuleInitializer] + public static void InitializeCompilation() + { + // Add project namespace. + var globalUsings = """ +global using System; +global using System.Threading; +global using System.Threading.Tasks; +global using System.ComponentModel.DataAnnotations; +global using MasterMemory; +"""; + + var references = AppDomain.CurrentDomain.GetAssemblies() + .Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location)) + .Select(x => MetadataReference.CreateFromFile(x.Location)) + .Concat(GetSelfReferences()); + + var compilation = CSharpCompilation.Create("generatortest", + references: references, + syntaxTrees: [CSharpSyntaxTree.ParseText(globalUsings, path: "GlobalUsings.cs")], + options: new CSharpCompilationOptions(OutputKind.ConsoleApplication, allowUnsafe: true)); // .exe + + baseCompilation = compilation; + + static IEnumerable GetSelfReferences() + { + // MasterMemory.Annotations + yield return MetadataReference.CreateFromFile(typeof(MasterMemory.MemoryTableAttribute).Assembly.Location); + } + } + + public static (Compilation, ImmutableArray) RunGenerator([StringSyntax("C#-test")] string source, string[]? preprocessorSymbols = null, AnalyzerConfigOptionsProvider? options = null) + { + if (preprocessorSymbols == null) + { + preprocessorSymbols = new[] { "NET8_0_OR_GREATER" }; + } + var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp12, preprocessorSymbols: preprocessorSymbols); // 12 + + // Create SourceGenerator + var driver = CSharpGeneratorDriver.Create(new MasterMemoryGenerator()).WithUpdatedParseOptions(parseOptions); + if (options != null) + { + driver = (Microsoft.CodeAnalysis.CSharp.CSharpGeneratorDriver)driver.WithUpdatedAnalyzerConfigOptions(options); + } + + var compilation = baseCompilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source, parseOptions)); + + driver.RunGeneratorsAndUpdateCompilation(compilation, out var newCompilation, out var diagnostics); + return (newCompilation, diagnostics); + } + + public static (Compilation, ImmutableArray, string) CompileAndExecute(string source, string[] args, string[]? preprocessorSymbols = null, AnalyzerConfigOptionsProvider? options = null) + { + var (compilation, diagnostics) = RunGenerator(source, preprocessorSymbols, options); + + using var ms = new MemoryStream(); + var emitResult = compilation.Emit(ms); + if (!emitResult.Success) + { + throw new InvalidOperationException("Emit Failed\r\n" + string.Join("\r\n", emitResult.Diagnostics.Select(x => x.ToString()))); + } + + ms.Position = 0; + + // capture stdout log + // modify global stdout so can't run in parallel unit-test + var originalOut = Console.Out; + try + { + var stringWriter = new StringWriter(); + Console.SetOut(stringWriter); + + // load and invoke Main(args) + var loadContext = new AssemblyLoadContext("source-generator", isCollectible: true); // isCollectible to support Unload + var assembly = loadContext.LoadFromStream(ms); + assembly.EntryPoint!.Invoke(null, new object[] { args }); + loadContext.Unload(); + + return (compilation, diagnostics, stringWriter.ToString()); + } + finally + { + Console.SetOut(originalOut); + } + } + + public static (string Key, string Reasons)[][] GetIncrementalGeneratorTrackedStepsReasons(string keyPrefixFilter, params string[] sources) + { + var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp12); // 12 + var driver = CSharpGeneratorDriver.Create( + [new MasterMemoryGenerator().AsSourceGenerator()], + driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, trackIncrementalGeneratorSteps: true)) + .WithUpdatedParseOptions(parseOptions); + + var generatorResults = sources + .Select(source => + { + var compilation = baseCompilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source, parseOptions)); + driver = driver.RunGenerators(compilation); + return driver.GetRunResult().Results[0]; + }) + .ToArray(); + + var reasons = generatorResults + .Select(x => x.TrackedSteps + .Where(x => x.Key.StartsWith(keyPrefixFilter) || x.Key == "SourceOutput") + .Select(x => + { + if (x.Key == "SourceOutput") + { + var values = x.Value.Where(x => x.Inputs[0].Source.Name?.StartsWith(keyPrefixFilter) ?? false); + return ( + x.Key, + Reasons: string.Join(", ", values.SelectMany(x => x.Outputs).Select(x => x.Reason).ToArray()) + ); + } + else + { + return ( + Key: x.Key.Substring(keyPrefixFilter.Length), + Reasons: string.Join(", ", x.Value.SelectMany(x => x.Outputs).Select(x => x.Reason).ToArray()) + ); + } + }) + .OrderBy(x => x.Key) + .ToArray()) + .ToArray(); + + return reasons; + } +} diff --git a/tests/MasterMemory.SourceGenerator.Tests/Utility/CodeGeneratorHelper.cs b/tests/MasterMemory.SourceGenerator.Tests/Utility/CodeGeneratorHelper.cs new file mode 100644 index 0000000..2cc283b --- /dev/null +++ b/tests/MasterMemory.SourceGenerator.Tests/Utility/CodeGeneratorHelper.cs @@ -0,0 +1,130 @@ +using Microsoft.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +public class CodeGeneratorHelper(ITestOutputHelper output, string idPrefix) +{ + // Diagnostics Verify + + public void Ok([StringSyntax("C#-test")] string code, [CallerArgumentExpression("code")] string? codeExpr = null) + { + output.WriteLine(codeExpr); + + var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code); + foreach (var item in diagnostics) + { + output.WriteLine(item.ToString()); + } + OutputGeneratedCode(compilation); + + diagnostics.Length.Should().Be(0); + } + + public Dictionary GenerateCode([StringSyntax("C#-test")] string code, [CallerArgumentExpression("code")] string? codeExpr = null) + { + var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code); + foreach (var item in diagnostics) + { + output.WriteLine(item.ToString()); + } + diagnostics.Length.Should().Be(0); + + var dict = new Dictionary(); + foreach (var syntaxTree in compilation.SyntaxTrees) + { + // only shows ConsoleApp.Run/Builder generated code + if (!syntaxTree.FilePath.Contains("g.cs")) continue; + var generatedCode = syntaxTree.ToString(); + var fileName = Path.GetFileName(syntaxTree.FilePath); + dict.Add(fileName, generatedCode); + } + + return dict; + } + + public void Verify(int id, [StringSyntax("C#-test")] string code, string diagnosticsCodeSpan, [CallerArgumentExpression("code")] string? codeExpr = null) + { + output.WriteLine(codeExpr); + + var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code); + foreach (var item in diagnostics) + { + output.WriteLine(item.ToString()); + } + OutputGeneratedCode(compilation); + + diagnostics.Length.Should().Be(1); + diagnostics[0].Id.Should().Be(idPrefix + id.ToString("000")); + + var text = GetLocationText(diagnostics[0], compilation.SyntaxTrees); + text.Should().Be(diagnosticsCodeSpan); + } + + public (string, string)[] Verify([StringSyntax("C#-test")] string code, [CallerArgumentExpression("code")] string? codeExpr = null) + { + output.WriteLine(codeExpr); + + var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator(code); + OutputGeneratedCode(compilation); + return diagnostics.Select(x => (x.Id, GetLocationText(x, compilation.SyntaxTrees))).ToArray(); + } + + // Execute and check stdout result + + public void Execute([StringSyntax("C#-test")] string code, string args, string expected, [CallerArgumentExpression("code")] string? codeExpr = null) + { + output.WriteLine(codeExpr); + + var (compilation, diagnostics, stdout) = CSharpGeneratorRunner.CompileAndExecute(code, args == "" ? [] : args.Split(' ')); + foreach (var item in diagnostics) + { + output.WriteLine(item.ToString()); + } + OutputGeneratedCode(compilation); + + stdout.Should().Be(expected); + } + + public string Error([StringSyntax("C#-test")] string code, string args, [CallerArgumentExpression("code")] string? codeExpr = null) + { + output.WriteLine(codeExpr); + + var (compilation, diagnostics, stdout) = CSharpGeneratorRunner.CompileAndExecute(code, args == "" ? [] : args.Split(' ')); + foreach (var item in diagnostics) + { + output.WriteLine(item.ToString()); + } + OutputGeneratedCode(compilation); + + return stdout; + } + + string GetLocationText(Diagnostic diagnostic, IEnumerable syntaxTrees) + { + var location = diagnostic.Location; + + var textSpan = location.SourceSpan; + var sourceTree = location.SourceTree; + if (sourceTree == null) + { + var lineSpan = location.GetLineSpan(); + if (lineSpan.Path == null) return ""; + + sourceTree = syntaxTrees.FirstOrDefault(x => x.FilePath == lineSpan.Path); + if (sourceTree == null) return ""; + } + + var text = sourceTree.GetText().GetSubText(textSpan).ToString(); + return text; + } + + void OutputGeneratedCode(Compilation compilation) + { + foreach (var syntaxTree in compilation.SyntaxTrees) + { + // only shows ConsoleApp.Run/Builder generated code + if (!syntaxTree.FilePath.Contains("g.cs")) continue; + output.WriteLine(syntaxTree.ToString()); + } + } +} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/DatabaseBuilder.cs b/tests/MasterMemory.Tests/Generated/DatabaseBuilder.cs deleted file mode 100644 index 3379a27..0000000 --- a/tests/MasterMemory.Tests/Generated/DatabaseBuilder.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public sealed class DatabaseBuilder : DatabaseBuilderBase - { - public DatabaseBuilder() : this(null) { } - public DatabaseBuilder(MessagePack.IFormatterResolver resolver) : base(resolver) { } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.ItemId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.ItemId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.RandomId, System.StringComparer.Ordinal); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.QuestId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.QuestId, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Id, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.TestID, System.Collections.Generic.Comparer.Default); - return this; - } - - public DatabaseBuilder Append(System.Collections.Generic.IEnumerable dataSource) - { - AppendCore(dataSource, x => x.Level, System.Collections.Generic.Comparer.Default); - return this; - } - - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/ImmutableBuilder.cs b/tests/MasterMemory.Tests/Generated/ImmutableBuilder.cs deleted file mode 100644 index 7d605ab..0000000 --- a/tests/MasterMemory.Tests/Generated/ImmutableBuilder.cs +++ /dev/null @@ -1,767 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public sealed class ImmutableBuilder : ImmutableBuilderBase - { - MemoryDatabase memory; - - public ImmutableBuilder(MemoryDatabase memory) - { - this.memory = memory; - } - - public MemoryDatabase Build() - { - return memory; - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new FailTable(newData); - memory = new MemoryDatabase( - table, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveFail(int[] keys) - { - var data = RemoveCore(memory.FailTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new FailTable(newData); - memory = new MemoryDatabase( - table, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(Fail[] addOrReplaceData) - { - var data = DiffCore(memory.FailTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new FailTable(newData); - memory = new MemoryDatabase( - table, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - table, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveItemMaster(int[] keys) - { - var data = RemoveCore(memory.ItemMasterTable.GetRawDataUnsafe(), keys, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - table, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(ItemMaster[] addOrReplaceData) - { - var data = DiffCore(memory.ItemMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - table, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - table, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveItemMasterEmptyValidate(int[] keys) - { - var data = RemoveCore(memory.ItemMasterEmptyValidateTable.GetRawDataUnsafe(), keys, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - table, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(ItemMasterEmptyValidate[] addOrReplaceData) - { - var data = DiffCore(memory.ItemMasterEmptyValidateTable.GetRawDataUnsafe(), addOrReplaceData, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.ItemId, System.Collections.Generic.Comparer.Default); - var table = new ItemMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - table, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.RandomId, System.StringComparer.Ordinal); - var table = new PersonModelTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - table, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemovePersonModel(string[] keys) - { - var data = RemoveCore(memory.PersonModelTable.GetRawDataUnsafe(), keys, x => x.RandomId, System.StringComparer.Ordinal); - var newData = CloneAndSortBy(data, x => x.RandomId, System.StringComparer.Ordinal); - var table = new PersonModelTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - table, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(PersonModel[] addOrReplaceData) - { - var data = DiffCore(memory.PersonModelTable.GetRawDataUnsafe(), addOrReplaceData, x => x.RandomId, System.StringComparer.Ordinal); - var newData = CloneAndSortBy(data, x => x.RandomId, System.StringComparer.Ordinal); - var table = new PersonModelTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - table, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - table, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveQuestMaster(int[] keys) - { - var data = RemoveCore(memory.QuestMasterTable.GetRawDataUnsafe(), keys, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - table, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(QuestMaster[] addOrReplaceData) - { - var data = DiffCore(memory.QuestMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - table, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - table, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveQuestMasterEmptyValidate(int[] keys) - { - var data = RemoveCore(memory.QuestMasterEmptyValidateTable.GetRawDataUnsafe(), keys, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - table, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(QuestMasterEmptyValidate[] addOrReplaceData) - { - var data = DiffCore(memory.QuestMasterEmptyValidateTable.GetRawDataUnsafe(), addOrReplaceData, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.QuestId, System.Collections.Generic.Comparer.Default); - var table = new QuestMasterEmptyValidateTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - table, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SampleTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - table, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSample(int[] keys) - { - var data = RemoveCore(memory.SampleTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SampleTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - table, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(Sample[] addOrReplaceData) - { - var data = DiffCore(memory.SampleTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SampleTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - table, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SequentialCheckMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - table, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSequentialCheckMaster(int[] keys) - { - var data = RemoveCore(memory.SequentialCheckMasterTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SequentialCheckMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - table, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(SequentialCheckMaster[] addOrReplaceData) - { - var data = DiffCore(memory.SequentialCheckMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SequentialCheckMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - table, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SingleMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - table, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSingleMaster(int[] keys) - { - var data = RemoveCore(memory.SingleMasterTable.GetRawDataUnsafe(), keys, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SingleMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - table, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(SingleMaster[] addOrReplaceData) - { - var data = DiffCore(memory.SingleMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Id, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Id, System.Collections.Generic.Comparer.Default); - var table = new SingleMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - table, - memory.SkillMasterTable, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var table = new SkillMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - table, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void RemoveSkillMaster((int SkillId, int SkillLevel)[] keys) - { - var data = RemoveCore(memory.SkillMasterTable.GetRawDataUnsafe(), keys, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var newData = CloneAndSortBy(data, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var table = new SkillMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - table, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void Diff(SkillMaster[] addOrReplaceData) - { - var data = DiffCore(memory.SkillMasterTable.GetRawDataUnsafe(), addOrReplaceData, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var newData = CloneAndSortBy(data, x => (x.SkillId, x.SkillLevel), System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default); - var table = new SkillMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - table, - memory.TestMasterTable, - memory.UserLevelTable - - ); - } - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.TestID, System.Collections.Generic.Comparer.Default); - var table = new TestMasterTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - table, - memory.UserLevelTable - - ); - } - - - public void ReplaceAll(System.Collections.Generic.IList data) - { - var newData = CloneAndSortBy(data, x => x.Level, System.Collections.Generic.Comparer.Default); - var table = new UserLevelTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - table - - ); - } - - public void RemoveUserLevel(int[] keys) - { - var data = RemoveCore(memory.UserLevelTable.GetRawDataUnsafe(), keys, x => x.Level, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Level, System.Collections.Generic.Comparer.Default); - var table = new UserLevelTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - table - - ); - } - - public void Diff(UserLevel[] addOrReplaceData) - { - var data = DiffCore(memory.UserLevelTable.GetRawDataUnsafe(), addOrReplaceData, x => x.Level, System.Collections.Generic.Comparer.Default); - var newData = CloneAndSortBy(data, x => x.Level, System.Collections.Generic.Comparer.Default); - var table = new UserLevelTable(newData); - memory = new MemoryDatabase( - memory.FailTable, - memory.ItemMasterTable, - memory.ItemMasterEmptyValidateTable, - memory.PersonModelTable, - memory.QuestMasterTable, - memory.QuestMasterEmptyValidateTable, - memory.SampleTable, - memory.SequentialCheckMasterTable, - memory.SingleMasterTable, - memory.SkillMasterTable, - memory.TestMasterTable, - table - - ); - } - - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/MasterMemoryResolver.cs b/tests/MasterMemory.Tests/Generated/MasterMemoryResolver.cs deleted file mode 100644 index 55e64ac..0000000 --- a/tests/MasterMemory.Tests/Generated/MasterMemoryResolver.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public class MasterMemoryResolver : global::MessagePack.IFormatterResolver - { - public static readonly global::MessagePack.IFormatterResolver Instance = new MasterMemoryResolver(); - - MasterMemoryResolver() - { - - } - - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() - { - return FormatterCache.formatter; - } - - static class FormatterCache - { - public static readonly global::MessagePack.Formatters.IMessagePackFormatter formatter; - - static FormatterCache() - { - var f = MasterMemoryResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (f != null) - { - formatter = (global::MessagePack.Formatters.IMessagePackFormatter)f; - } - } - } - } - - internal static class MasterMemoryResolverGetFormatterHelper - { - static readonly global::System.Collections.Generic.Dictionary lookup; - - static MasterMemoryResolverGetFormatterHelper() - { - lookup = new global::System.Collections.Generic.Dictionary(12) - { - {typeof(Fail[]), 0 }, - {typeof(ItemMaster[]), 1 }, - {typeof(ItemMasterEmptyValidate[]), 2 }, - {typeof(PersonModel[]), 3 }, - {typeof(QuestMaster[]), 4 }, - {typeof(QuestMasterEmptyValidate[]), 5 }, - {typeof(Sample[]), 6 }, - {typeof(SequentialCheckMaster[]), 7 }, - {typeof(SingleMaster[]), 8 }, - {typeof(SkillMaster[]), 9 }, - {typeof(TestMaster[]), 10 }, - {typeof(UserLevel[]), 11 }, - }; - } - - internal static object GetFormatter(Type t) - { - int key; - if (!lookup.TryGetValue(t, out key)) return null; - - switch (key) - { - case 0: return new MessagePack.Formatters.ArrayFormatter(); - case 1: return new MessagePack.Formatters.ArrayFormatter(); - case 2: return new MessagePack.Formatters.ArrayFormatter(); - case 3: return new MessagePack.Formatters.ArrayFormatter(); - case 4: return new MessagePack.Formatters.ArrayFormatter(); - case 5: return new MessagePack.Formatters.ArrayFormatter(); - case 6: return new MessagePack.Formatters.ArrayFormatter(); - case 7: return new MessagePack.Formatters.ArrayFormatter(); - case 8: return new MessagePack.Formatters.ArrayFormatter(); - case 9: return new MessagePack.Formatters.ArrayFormatter(); - case 10: return new MessagePack.Formatters.ArrayFormatter(); - case 11: return new MessagePack.Formatters.ArrayFormatter(); - default: return null; - } - } - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/MemoryDatabase.cs b/tests/MasterMemory.Tests/Generated/MemoryDatabase.cs deleted file mode 100644 index 657a88d..0000000 --- a/tests/MasterMemory.Tests/Generated/MemoryDatabase.cs +++ /dev/null @@ -1,270 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; -using MasterMemory.Tests.Tables; - -namespace MasterMemory.Tests -{ - public sealed class MemoryDatabase : MemoryDatabaseBase - { - public FailTable FailTable { get; private set; } - public ItemMasterTable ItemMasterTable { get; private set; } - public ItemMasterEmptyValidateTable ItemMasterEmptyValidateTable { get; private set; } - public PersonModelTable PersonModelTable { get; private set; } - public QuestMasterTable QuestMasterTable { get; private set; } - public QuestMasterEmptyValidateTable QuestMasterEmptyValidateTable { get; private set; } - public SampleTable SampleTable { get; private set; } - public SequentialCheckMasterTable SequentialCheckMasterTable { get; private set; } - public SingleMasterTable SingleMasterTable { get; private set; } - public SkillMasterTable SkillMasterTable { get; private set; } - public TestMasterTable TestMasterTable { get; private set; } - public UserLevelTable UserLevelTable { get; private set; } - - public MemoryDatabase( - FailTable FailTable, - ItemMasterTable ItemMasterTable, - ItemMasterEmptyValidateTable ItemMasterEmptyValidateTable, - PersonModelTable PersonModelTable, - QuestMasterTable QuestMasterTable, - QuestMasterEmptyValidateTable QuestMasterEmptyValidateTable, - SampleTable SampleTable, - SequentialCheckMasterTable SequentialCheckMasterTable, - SingleMasterTable SingleMasterTable, - SkillMasterTable SkillMasterTable, - TestMasterTable TestMasterTable, - UserLevelTable UserLevelTable - ) - { - this.FailTable = FailTable; - this.ItemMasterTable = ItemMasterTable; - this.ItemMasterEmptyValidateTable = ItemMasterEmptyValidateTable; - this.PersonModelTable = PersonModelTable; - this.QuestMasterTable = QuestMasterTable; - this.QuestMasterEmptyValidateTable = QuestMasterEmptyValidateTable; - this.SampleTable = SampleTable; - this.SequentialCheckMasterTable = SequentialCheckMasterTable; - this.SingleMasterTable = SingleMasterTable; - this.SkillMasterTable = SkillMasterTable; - this.TestMasterTable = TestMasterTable; - this.UserLevelTable = UserLevelTable; - } - - public MemoryDatabase(byte[] databaseBinary, bool internString = true, MessagePack.IFormatterResolver formatterResolver = null, int maxDegreeOfParallelism = 1) - : base(databaseBinary, internString, formatterResolver, maxDegreeOfParallelism) - { - } - - protected override void Init(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - if(maxDegreeOfParallelism == 1) - { - InitSequential(header, databaseBinary, options, maxDegreeOfParallelism); - } - else - { - InitParallel(header, databaseBinary, options, maxDegreeOfParallelism); - } - } - - void InitSequential(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - this.FailTable = ExtractTableData(header, databaseBinary, options, xs => new FailTable(xs)); - this.ItemMasterTable = ExtractTableData(header, databaseBinary, options, xs => new ItemMasterTable(xs)); - this.ItemMasterEmptyValidateTable = ExtractTableData(header, databaseBinary, options, xs => new ItemMasterEmptyValidateTable(xs)); - this.PersonModelTable = ExtractTableData(header, databaseBinary, options, xs => new PersonModelTable(xs)); - this.QuestMasterTable = ExtractTableData(header, databaseBinary, options, xs => new QuestMasterTable(xs)); - this.QuestMasterEmptyValidateTable = ExtractTableData(header, databaseBinary, options, xs => new QuestMasterEmptyValidateTable(xs)); - this.SampleTable = ExtractTableData(header, databaseBinary, options, xs => new SampleTable(xs)); - this.SequentialCheckMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SequentialCheckMasterTable(xs)); - this.SingleMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SingleMasterTable(xs)); - this.SkillMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SkillMasterTable(xs)); - this.TestMasterTable = ExtractTableData(header, databaseBinary, options, xs => new TestMasterTable(xs)); - this.UserLevelTable = ExtractTableData(header, databaseBinary, options, xs => new UserLevelTable(xs)); - } - - void InitParallel(Dictionary header, System.ReadOnlyMemory databaseBinary, MessagePack.MessagePackSerializerOptions options, int maxDegreeOfParallelism) - { - var extracts = new Action[] - { - () => this.FailTable = ExtractTableData(header, databaseBinary, options, xs => new FailTable(xs)), - () => this.ItemMasterTable = ExtractTableData(header, databaseBinary, options, xs => new ItemMasterTable(xs)), - () => this.ItemMasterEmptyValidateTable = ExtractTableData(header, databaseBinary, options, xs => new ItemMasterEmptyValidateTable(xs)), - () => this.PersonModelTable = ExtractTableData(header, databaseBinary, options, xs => new PersonModelTable(xs)), - () => this.QuestMasterTable = ExtractTableData(header, databaseBinary, options, xs => new QuestMasterTable(xs)), - () => this.QuestMasterEmptyValidateTable = ExtractTableData(header, databaseBinary, options, xs => new QuestMasterEmptyValidateTable(xs)), - () => this.SampleTable = ExtractTableData(header, databaseBinary, options, xs => new SampleTable(xs)), - () => this.SequentialCheckMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SequentialCheckMasterTable(xs)), - () => this.SingleMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SingleMasterTable(xs)), - () => this.SkillMasterTable = ExtractTableData(header, databaseBinary, options, xs => new SkillMasterTable(xs)), - () => this.TestMasterTable = ExtractTableData(header, databaseBinary, options, xs => new TestMasterTable(xs)), - () => this.UserLevelTable = ExtractTableData(header, databaseBinary, options, xs => new UserLevelTable(xs)), - }; - - System.Threading.Tasks.Parallel.ForEach(extracts, new System.Threading.Tasks.ParallelOptions - { - MaxDegreeOfParallelism = maxDegreeOfParallelism - }, action => action.Invoke()); - } - - public ImmutableBuilder ToImmutableBuilder() - { - return new ImmutableBuilder(this); - } - - public DatabaseBuilder ToDatabaseBuilder() - { - var builder = new DatabaseBuilder(); - builder.Append(this.FailTable.GetRawDataUnsafe()); - builder.Append(this.ItemMasterTable.GetRawDataUnsafe()); - builder.Append(this.ItemMasterEmptyValidateTable.GetRawDataUnsafe()); - builder.Append(this.PersonModelTable.GetRawDataUnsafe()); - builder.Append(this.QuestMasterTable.GetRawDataUnsafe()); - builder.Append(this.QuestMasterEmptyValidateTable.GetRawDataUnsafe()); - builder.Append(this.SampleTable.GetRawDataUnsafe()); - builder.Append(this.SequentialCheckMasterTable.GetRawDataUnsafe()); - builder.Append(this.SingleMasterTable.GetRawDataUnsafe()); - builder.Append(this.SkillMasterTable.GetRawDataUnsafe()); - builder.Append(this.TestMasterTable.GetRawDataUnsafe()); - builder.Append(this.UserLevelTable.GetRawDataUnsafe()); - return builder; - } - - public DatabaseBuilder ToDatabaseBuilder(MessagePack.IFormatterResolver resolver) - { - var builder = new DatabaseBuilder(resolver); - builder.Append(this.FailTable.GetRawDataUnsafe()); - builder.Append(this.ItemMasterTable.GetRawDataUnsafe()); - builder.Append(this.ItemMasterEmptyValidateTable.GetRawDataUnsafe()); - builder.Append(this.PersonModelTable.GetRawDataUnsafe()); - builder.Append(this.QuestMasterTable.GetRawDataUnsafe()); - builder.Append(this.QuestMasterEmptyValidateTable.GetRawDataUnsafe()); - builder.Append(this.SampleTable.GetRawDataUnsafe()); - builder.Append(this.SequentialCheckMasterTable.GetRawDataUnsafe()); - builder.Append(this.SingleMasterTable.GetRawDataUnsafe()); - builder.Append(this.SkillMasterTable.GetRawDataUnsafe()); - builder.Append(this.TestMasterTable.GetRawDataUnsafe()); - builder.Append(this.UserLevelTable.GetRawDataUnsafe()); - return builder; - } - -#if !DISABLE_MASTERMEMORY_VALIDATOR - - public ValidateResult Validate() - { - var result = new ValidateResult(); - var database = new ValidationDatabase(new object[] - { - FailTable, - ItemMasterTable, - ItemMasterEmptyValidateTable, - PersonModelTable, - QuestMasterTable, - QuestMasterEmptyValidateTable, - SampleTable, - SequentialCheckMasterTable, - SingleMasterTable, - SkillMasterTable, - TestMasterTable, - UserLevelTable, - }); - - ((ITableUniqueValidate)FailTable).ValidateUnique(result); - ValidateTable(FailTable.All, database, "Id", FailTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)ItemMasterTable).ValidateUnique(result); - ValidateTable(ItemMasterTable.All, database, "ItemId", ItemMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)ItemMasterEmptyValidateTable).ValidateUnique(result); - ValidateTable(ItemMasterEmptyValidateTable.All, database, "ItemId", ItemMasterEmptyValidateTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)PersonModelTable).ValidateUnique(result); - ValidateTable(PersonModelTable.All, database, "RandomId", PersonModelTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)QuestMasterTable).ValidateUnique(result); - ValidateTable(QuestMasterTable.All, database, "QuestId", QuestMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)QuestMasterEmptyValidateTable).ValidateUnique(result); - ValidateTable(QuestMasterEmptyValidateTable.All, database, "QuestId", QuestMasterEmptyValidateTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SampleTable).ValidateUnique(result); - ValidateTable(SampleTable.All, database, "Id", SampleTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SequentialCheckMasterTable).ValidateUnique(result); - ValidateTable(SequentialCheckMasterTable.All, database, "Id", SequentialCheckMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SingleMasterTable).ValidateUnique(result); - ValidateTable(SingleMasterTable.All, database, "Id", SingleMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)SkillMasterTable).ValidateUnique(result); - ValidateTable(SkillMasterTable.All, database, "(SkillId, SkillLevel)", SkillMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)TestMasterTable).ValidateUnique(result); - ValidateTable(TestMasterTable.All, database, "TestID", TestMasterTable.PrimaryKeySelector, result); - ((ITableUniqueValidate)UserLevelTable).ValidateUnique(result); - ValidateTable(UserLevelTable.All, database, "Level", UserLevelTable.PrimaryKeySelector, result); - - return result; - } - -#endif - - static MasterMemory.Meta.MetaDatabase metaTable; - - public static object GetTable(MemoryDatabase db, string tableName) - { - switch (tableName) - { - case "fail": - return db.FailTable; - case "item_master": - return db.ItemMasterTable; - case "item_master_empty": - return db.ItemMasterEmptyValidateTable; - case "people": - return db.PersonModelTable; - case "quest_master": - return db.QuestMasterTable; - case "quest_master_empty": - return db.QuestMasterEmptyValidateTable; - case "s_a_m_p_l_e": - return db.SampleTable; - case "sequantial_master": - return db.SequentialCheckMasterTable; - case "single_master": - return db.SingleMasterTable; - case "skillmaster": - return db.SkillMasterTable; - case "TestMaster": - return db.TestMasterTable; - case "UserLevel": - return db.UserLevelTable; - - default: - return null; - } - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaDatabase GetMetaDatabase() - { - if (metaTable != null) return metaTable; - - var dict = new Dictionary(); - dict.Add("fail", MasterMemory.Tests.Tables.FailTable.CreateMetaTable()); - dict.Add("item_master", MasterMemory.Tests.Tables.ItemMasterTable.CreateMetaTable()); - dict.Add("item_master_empty", MasterMemory.Tests.Tables.ItemMasterEmptyValidateTable.CreateMetaTable()); - dict.Add("people", MasterMemory.Tests.Tables.PersonModelTable.CreateMetaTable()); - dict.Add("quest_master", MasterMemory.Tests.Tables.QuestMasterTable.CreateMetaTable()); - dict.Add("quest_master_empty", MasterMemory.Tests.Tables.QuestMasterEmptyValidateTable.CreateMetaTable()); - dict.Add("s_a_m_p_l_e", MasterMemory.Tests.Tables.SampleTable.CreateMetaTable()); - dict.Add("sequantial_master", MasterMemory.Tests.Tables.SequentialCheckMasterTable.CreateMetaTable()); - dict.Add("single_master", MasterMemory.Tests.Tables.SingleMasterTable.CreateMetaTable()); - dict.Add("skillmaster", MasterMemory.Tests.Tables.SkillMasterTable.CreateMetaTable()); - dict.Add("TestMaster", MasterMemory.Tests.Tables.TestMasterTable.CreateMetaTable()); - dict.Add("UserLevel", MasterMemory.Tests.Tables.UserLevelTable.CreateMetaTable()); - - metaTable = new MasterMemory.Meta.MetaDatabase(dict); - return metaTable; - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/MessagePackGenerated.cs b/tests/MasterMemory.Tests/Generated/MessagePackGenerated.cs deleted file mode 100644 index b871bbd..0000000 --- a/tests/MasterMemory.Tests/Generated/MessagePackGenerated.cs +++ /dev/null @@ -1,1114 +0,0 @@ -// -// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT. -// - -#pragma warning disable 618 -#pragma warning disable 612 -#pragma warning disable 414 -#pragma warning disable 168 - -#pragma warning disable SA1200 // Using directives should be placed correctly -#pragma warning disable SA1312 // Variable names should begin with lower-case letter -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Resolvers -{ - using System; - using System.Buffers; - using MessagePack; - - public class GeneratedResolver : global::MessagePack.IFormatterResolver - { - public static readonly global::MessagePack.IFormatterResolver Instance = new GeneratedResolver(); - - private GeneratedResolver() - { - } - - public global::MessagePack.Formatters.IMessagePackFormatter GetFormatter() - { - return FormatterCache.Formatter; - } - - private static class FormatterCache - { - internal static readonly global::MessagePack.Formatters.IMessagePackFormatter Formatter; - - static FormatterCache() - { - var f = GeneratedResolverGetFormatterHelper.GetFormatter(typeof(T)); - if (f != null) - { - Formatter = (global::MessagePack.Formatters.IMessagePackFormatter)f; - } - } - } - } - - internal static class GeneratedResolverGetFormatterHelper - { - private static readonly global::System.Collections.Generic.Dictionary lookup; - - static GeneratedResolverGetFormatterHelper() - { - lookup = new global::System.Collections.Generic.Dictionary(11) - { - { typeof(global::MasterMemory.Tests.TestStructures.QuestMaster), 0 }, - { typeof(global::MasterMemory.Tests.TestStructures.ItemMaster), 1 }, - { typeof(global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate), 2 }, - { typeof(global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate), 3 }, - { typeof(global::MasterMemory.Tests.TestStructures.SequentialCheckMaster), 4 }, - { typeof(global::MasterMemory.Tests.TestStructures.SingleMaster), 5 }, - { typeof(global::MasterMemory.Tests.TestStructures.Fail), 6 }, - { typeof(global::MasterMemory.Tests.Sample), 7 }, - { typeof(global::MasterMemory.Tests.SkillMaster), 8 }, - { typeof(global::MasterMemory.Tests.TestStructures.TestMaster), 9 }, - { typeof(global::MasterMemory.Tests.UserLevel), 10 }, - }; - } - - internal static object GetFormatter(Type t) - { - int key; - if (!lookup.TryGetValue(t, out key)) - { - return null; - } - - switch (key) - { - case 0: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.QuestMasterFormatter(); - case 1: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.ItemMasterFormatter(); - case 2: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.QuestMasterEmptyValidateFormatter(); - case 3: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.ItemMasterEmptyValidateFormatter(); - case 4: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.SequentialCheckMasterFormatter(); - case 5: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.SingleMasterFormatter(); - case 6: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.FailFormatter(); - case 7: return new MessagePack.Formatters.MasterMemory.Tests.SampleFormatter(); - case 8: return new MessagePack.Formatters.MasterMemory.Tests.SkillMasterFormatter(); - case 9: return new MessagePack.Formatters.MasterMemory.Tests.TestStructures.TestMasterFormatter(); - case 10: return new MessagePack.Formatters.MasterMemory.Tests.UserLevelFormatter(); - default: return null; - } - } - } -} - -#pragma warning restore 168 -#pragma warning restore 414 -#pragma warning restore 618 -#pragma warning restore 612 - -#pragma warning restore SA1312 // Variable names should begin with lower-case letter -#pragma warning restore SA1200 // Using directives should be placed correctly -#pragma warning restore SA1649 // File name should match first type name - - - - -// -// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT. -// - -#pragma warning disable 618 -#pragma warning disable 612 -#pragma warning disable 414 -#pragma warning disable 168 - -#pragma warning disable SA1129 // Do not use default value type constructor -#pragma warning disable SA1200 // Using directives should be placed correctly -#pragma warning disable SA1309 // Field names should not begin with underscore -#pragma warning disable SA1312 // Variable names should begin with lower-case letter -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters.MasterMemory.Tests.TestStructures -{ - using System; - using System.Buffers; - using MessagePack; - - public sealed class QuestMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public QuestMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "QuestId", 0 }, - { "Name", 1 }, - { "RewardItemId", 2 }, - { "Cost", 3 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("QuestId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Name"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("RewardItemId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Cost"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.QuestMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(4); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.QuestId); - writer.WriteRaw(this.____stringByteKeys[1]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.Name, options); - writer.WriteRaw(this.____stringByteKeys[2]); - writer.Write(value.RewardItemId); - writer.WriteRaw(this.____stringByteKeys[3]); - writer.Write(value.Cost); - } - - public global::MasterMemory.Tests.TestStructures.QuestMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __QuestId__ = default(int); - var __Name__ = default(string); - var __RewardItemId__ = default(int); - var __Cost__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __QuestId__ = reader.ReadInt32(); - break; - case 1: - __Name__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __RewardItemId__ = reader.ReadInt32(); - break; - case 3: - __Cost__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.QuestMaster(); - ____result.QuestId = __QuestId__; - ____result.Name = __Name__; - ____result.RewardItemId = __RewardItemId__; - ____result.Cost = __Cost__; - return ____result; - } - } - - public sealed class ItemMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public ItemMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "ItemId", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("ItemId"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.ItemMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.ItemId); - } - - public global::MasterMemory.Tests.TestStructures.ItemMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __ItemId__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __ItemId__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.ItemMaster(); - ____result.ItemId = __ItemId__; - return ____result; - } - } - - public sealed class QuestMasterEmptyValidateFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public QuestMasterEmptyValidateFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "QuestId", 0 }, - { "Name", 1 }, - { "RewardItemId", 2 }, - { "Cost", 3 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("QuestId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Name"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("RewardItemId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Cost"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(4); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.QuestId); - writer.WriteRaw(this.____stringByteKeys[1]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.Name, options); - writer.WriteRaw(this.____stringByteKeys[2]); - writer.Write(value.RewardItemId); - writer.WriteRaw(this.____stringByteKeys[3]); - writer.Write(value.Cost); - } - - public global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __QuestId__ = default(int); - var __Name__ = default(string); - var __RewardItemId__ = default(int); - var __Cost__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __QuestId__ = reader.ReadInt32(); - break; - case 1: - __Name__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 2: - __RewardItemId__ = reader.ReadInt32(); - break; - case 3: - __Cost__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.QuestMasterEmptyValidate(); - ____result.QuestId = __QuestId__; - ____result.Name = __Name__; - ____result.RewardItemId = __RewardItemId__; - ____result.Cost = __Cost__; - return ____result; - } - } - - public sealed class ItemMasterEmptyValidateFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public ItemMasterEmptyValidateFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "ItemId", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("ItemId"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.ItemId); - } - - public global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __ItemId__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __ItemId__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.ItemMasterEmptyValidate(); - ____result.ItemId = __ItemId__; - return ____result; - } - } - - public sealed class SequentialCheckMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SequentialCheckMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - { "Cost", 1 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Cost"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.SequentialCheckMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(2); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Cost); - } - - public global::MasterMemory.Tests.TestStructures.SequentialCheckMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - var __Cost__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - case 1: - __Cost__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.SequentialCheckMaster(); - ____result.Id = __Id__; - ____result.Cost = __Cost__; - return ____result; - } - } - - public sealed class SingleMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SingleMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.SingleMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - } - - public global::MasterMemory.Tests.TestStructures.SingleMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.SingleMaster(); - ____result.Id = __Id__; - return ____result; - } - } - - public sealed class FailFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public FailFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.Fail value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(1); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - } - - public global::MasterMemory.Tests.TestStructures.Fail Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.Fail(); - ____result.Id = __Id__; - return ____result; - } - } - - public sealed class TestMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public TestMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "TestID", 0 }, - { "Value", 1 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("TestID"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Value"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.TestStructures.TestMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(2); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.TestID); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Value); - } - - public global::MasterMemory.Tests.TestStructures.TestMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __TestID__ = default(int); - var __Value__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __TestID__ = reader.ReadInt32(); - break; - case 1: - __Value__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.TestStructures.TestMaster(__TestID__, __Value__); - ____result.TestID = __TestID__; - ____result.Value = __Value__; - return ____result; - } - } -} - -#pragma warning restore 168 -#pragma warning restore 414 -#pragma warning restore 618 -#pragma warning restore 612 - -#pragma warning restore SA1129 // Do not use default value type constructor -#pragma warning restore SA1200 // Using directives should be placed correctly -#pragma warning restore SA1309 // Field names should not begin with underscore -#pragma warning restore SA1312 // Variable names should begin with lower-case letter -#pragma warning restore SA1403 // File may only contain a single namespace -#pragma warning restore SA1649 // File name should match first type name - -// -// THIS (.cs) FILE IS GENERATED BY MPC(MessagePack-CSharp). DO NOT CHANGE IT. -// - -#pragma warning disable 618 -#pragma warning disable 612 -#pragma warning disable 414 -#pragma warning disable 168 - -#pragma warning disable SA1129 // Do not use default value type constructor -#pragma warning disable SA1200 // Using directives should be placed correctly -#pragma warning disable SA1309 // Field names should not begin with underscore -#pragma warning disable SA1312 // Variable names should begin with lower-case letter -#pragma warning disable SA1403 // File may only contain a single namespace -#pragma warning disable SA1649 // File name should match first type name - -namespace MessagePack.Formatters.MasterMemory.Tests -{ - using System; - using System.Buffers; - using MessagePack; - - public sealed class SampleFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SampleFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Id", 0 }, - { "Age", 1 }, - { "FirstName", 2 }, - { "LastName", 3 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Id"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Age"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("FirstName"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("LastName"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.Sample value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(4); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Id); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Age); - writer.WriteRaw(this.____stringByteKeys[2]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.FirstName, options); - writer.WriteRaw(this.____stringByteKeys[3]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.LastName, options); - } - - public global::MasterMemory.Tests.Sample Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Id__ = default(int); - var __Age__ = default(int); - var __FirstName__ = default(string); - var __LastName__ = default(string); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Id__ = reader.ReadInt32(); - break; - case 1: - __Age__ = reader.ReadInt32(); - break; - case 2: - __FirstName__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 3: - __LastName__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.Sample(__Id__, __Age__, __FirstName__, __LastName__); - ____result.Id = __Id__; - ____result.Age = __Age__; - ____result.FirstName = __FirstName__; - ____result.LastName = __LastName__; - return ____result; - } - } - - public sealed class SkillMasterFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public SkillMasterFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "SkillId", 0 }, - { "SkillLevel", 1 }, - { "AttackPower", 2 }, - { "SkillName", 3 }, - { "Description", 4 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("SkillId"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("SkillLevel"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("AttackPower"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("SkillName"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Description"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.SkillMaster value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(5); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.SkillId); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.SkillLevel); - writer.WriteRaw(this.____stringByteKeys[2]); - writer.Write(value.AttackPower); - writer.WriteRaw(this.____stringByteKeys[3]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.SkillName, options); - writer.WriteRaw(this.____stringByteKeys[4]); - formatterResolver.GetFormatterWithVerify().Serialize(ref writer, value.Description, options); - } - - public global::MasterMemory.Tests.SkillMaster Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __SkillId__ = default(int); - var __SkillLevel__ = default(int); - var __AttackPower__ = default(int); - var __SkillName__ = default(string); - var __Description__ = default(string); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __SkillId__ = reader.ReadInt32(); - break; - case 1: - __SkillLevel__ = reader.ReadInt32(); - break; - case 2: - __AttackPower__ = reader.ReadInt32(); - break; - case 3: - __SkillName__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - case 4: - __Description__ = formatterResolver.GetFormatterWithVerify().Deserialize(ref reader, options); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.SkillMaster(__SkillId__, __SkillLevel__, __AttackPower__, __SkillName__, __Description__); - ____result.SkillId = __SkillId__; - ____result.SkillLevel = __SkillLevel__; - ____result.AttackPower = __AttackPower__; - ____result.SkillName = __SkillName__; - ____result.Description = __Description__; - return ____result; - } - } - - public sealed class UserLevelFormatter : global::MessagePack.Formatters.IMessagePackFormatter - { - - - private readonly global::MessagePack.Internal.AutomataDictionary ____keyMapping; - private readonly byte[][] ____stringByteKeys; - - public UserLevelFormatter() - { - this.____keyMapping = new global::MessagePack.Internal.AutomataDictionary() - { - { "Level", 0 }, - { "Exp", 1 }, - }; - - this.____stringByteKeys = new byte[][] - { - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Level"), - global::MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes("Exp"), - }; - } - - public void Serialize(ref MessagePackWriter writer, global::MasterMemory.Tests.UserLevel value, global::MessagePack.MessagePackSerializerOptions options) - { - if (value == null) - { - writer.WriteNil(); - return; - } - - IFormatterResolver formatterResolver = options.Resolver; - writer.WriteMapHeader(2); - writer.WriteRaw(this.____stringByteKeys[0]); - writer.Write(value.Level); - writer.WriteRaw(this.____stringByteKeys[1]); - writer.Write(value.Exp); - } - - public global::MasterMemory.Tests.UserLevel Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) - { - if (reader.TryReadNil()) - { - return null; - } - - IFormatterResolver formatterResolver = options.Resolver; - var length = reader.ReadMapHeader(); - var __Level__ = default(int); - var __Exp__ = default(int); - - for (int i = 0; i < length; i++) - { - ReadOnlySpan stringKey = Internal.CodeGenHelpers.ReadStringSpan(ref reader); - int key; - if (!this.____keyMapping.TryGetValue(stringKey, out key)) - { - reader.Skip(); - continue; - } - - switch (key) - { - case 0: - __Level__ = reader.ReadInt32(); - break; - case 1: - __Exp__ = reader.ReadInt32(); - break; - default: - reader.Skip(); - break; - } - } - - var ____result = new global::MasterMemory.Tests.UserLevel(__Level__, __Exp__); - ____result.Level = __Level__; - ____result.Exp = __Exp__; - return ____result; - } - } -} - -#pragma warning restore 168 -#pragma warning restore 414 -#pragma warning restore 618 -#pragma warning restore 612 - -#pragma warning restore SA1129 // Do not use default value type constructor -#pragma warning restore SA1200 // Using directives should be placed correctly -#pragma warning restore SA1309 // Field names should not begin with underscore -#pragma warning restore SA1312 // Variable names should begin with lower-case letter -#pragma warning restore SA1403 // File may only contain a single namespace -#pragma warning restore SA1649 // File name should match first type name - diff --git a/tests/MasterMemory.Tests/Generated/Tables/FailTable.cs b/tests/MasterMemory.Tests/Generated/Tables/FailTable.cs deleted file mode 100644 index 7694e06..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/FailTable.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class FailTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public FailTable(Fail[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Fail FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Fail result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Fail FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Fail), typeof(FailTable), "fail", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Fail).GetProperty("Id")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Fail).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs b/tests/MasterMemory.Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs deleted file mode 100644 index eae39e3..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/ItemMasterEmptyValidateTable.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class ItemMasterEmptyValidateTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public ItemMasterEmptyValidateTable(ItemMasterEmptyValidate[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.ItemId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public ItemMasterEmptyValidate FindByItemId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByItemId(int key, out ItemMasterEmptyValidate result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public ItemMasterEmptyValidate FindClosestByItemId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByItemId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "ItemId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(ItemMasterEmptyValidate), typeof(ItemMasterEmptyValidateTable), "item_master_empty", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(ItemMasterEmptyValidate).GetProperty("ItemId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(ItemMasterEmptyValidate).GetProperty("ItemId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/ItemMasterTable.cs b/tests/MasterMemory.Tests/Generated/Tables/ItemMasterTable.cs deleted file mode 100644 index 332cfdb..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/ItemMasterTable.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class ItemMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public ItemMasterTable(ItemMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.ItemId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public ItemMaster FindByItemId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByItemId(int key, out ItemMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].ItemId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public ItemMaster FindClosestByItemId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByItemId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "ItemId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(ItemMaster), typeof(ItemMasterTable), "item_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(ItemMaster).GetProperty("ItemId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(ItemMaster).GetProperty("ItemId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/PersonModelTable.cs b/tests/MasterMemory.Tests/Generated/Tables/PersonModelTable.cs deleted file mode 100644 index f35fdf0..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/PersonModelTable.cs +++ /dev/null @@ -1,149 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class PersonModelTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly PersonModel[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - readonly PersonModel[] secondaryIndex1; - readonly Func secondaryIndex1Selector; - readonly PersonModel[] secondaryIndex2; - readonly Func secondaryIndex2Selector; - - public PersonModelTable(PersonModel[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.RandomId; - this.secondaryIndex0Selector = x => x.LastName; - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.StringComparer.Ordinal); - this.secondaryIndex1Selector = x => (x.FirstName, x.LastName); - this.secondaryIndex1 = CloneAndSortBy(this.secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default); - this.secondaryIndex2Selector = x => x.FirstName; - this.secondaryIndex2 = CloneAndSortBy(this.secondaryIndex2Selector, System.StringComparer.Ordinal); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByLastName => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - public RangeView SortByFirstNameAndLastName => new RangeView(secondaryIndex1, 0, secondaryIndex1.Length - 1, true); - public RangeView SortByFirstName => new RangeView(secondaryIndex2, 0, secondaryIndex2.Length - 1, true); - - public PersonModel FindByRandomId(string key) - { - return FindUniqueCore(data, primaryIndexSelector, System.StringComparer.Ordinal, key, true); - } - - public bool TryFindByRandomId(string key, out PersonModel result) - { - return TryFindUniqueCore(data, primaryIndexSelector, System.StringComparer.Ordinal, key, out result); - } - - public PersonModel FindClosestByRandomId(string key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByRandomId(string min, string max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.StringComparer.Ordinal, min, max, ascendant); - } - - public RangeView FindByLastName(string key) - { - return FindManyCore(secondaryIndex0, secondaryIndex0Selector, System.StringComparer.Ordinal, key); - } - - public RangeView FindClosestByLastName(string key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex0, secondaryIndex0Selector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByLastName(string min, string max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex0, secondaryIndex0Selector, System.StringComparer.Ordinal, min, max, ascendant); - } - - public RangeView FindByFirstNameAndLastName((string FirstName, string LastName) key) - { - return FindManyCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key); - } - - public RangeView FindClosestByFirstNameAndLastName((string FirstName, string LastName) key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, selectLower); - } - - public RangeView FindRangeByFirstNameAndLastName((string FirstName, string LastName) min, (string FirstName, string LastName) max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, min, max, ascendant); - } - - public RangeView FindByFirstName(string key) - { - return FindManyCore(secondaryIndex2, secondaryIndex2Selector, System.StringComparer.Ordinal, key); - } - - public RangeView FindClosestByFirstName(string key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex2, secondaryIndex2Selector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByFirstName(string min, string max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex2, secondaryIndex2Selector, System.StringComparer.Ordinal, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "RandomId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(PersonModel), typeof(PersonModelTable), "people", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(PersonModel).GetProperty("LastName")), - new MasterMemory.Meta.MetaProperty(typeof(PersonModel).GetProperty("FirstName")), - new MasterMemory.Meta.MetaProperty(typeof(PersonModel).GetProperty("RandomId")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("RandomId"), - }, true, true, System.StringComparer.Ordinal), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("LastName"), - }, false, false, System.StringComparer.Ordinal), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("FirstName"), - typeof(PersonModel).GetProperty("LastName"), - }, false, false, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(PersonModel).GetProperty("FirstName"), - }, false, false, System.StringComparer.Ordinal), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs b/tests/MasterMemory.Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs deleted file mode 100644 index 820dc71..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/QuestMasterEmptyValidateTable.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class QuestMasterEmptyValidateTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public QuestMasterEmptyValidateTable(QuestMasterEmptyValidate[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.QuestId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public QuestMasterEmptyValidate FindByQuestId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByQuestId(int key, out QuestMasterEmptyValidate result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public QuestMasterEmptyValidate FindClosestByQuestId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByQuestId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "QuestId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(QuestMasterEmptyValidate), typeof(QuestMasterEmptyValidateTable), "quest_master_empty", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("QuestId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("Name")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("RewardItemId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMasterEmptyValidate).GetProperty("Cost")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(QuestMasterEmptyValidate).GetProperty("QuestId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/QuestMasterTable.cs b/tests/MasterMemory.Tests/Generated/Tables/QuestMasterTable.cs deleted file mode 100644 index 0e4d059..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/QuestMasterTable.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class QuestMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public QuestMasterTable(QuestMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.QuestId; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public QuestMaster FindByQuestId(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByQuestId(int key, out QuestMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].QuestId; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public QuestMaster FindClosestByQuestId(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByQuestId(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "QuestId", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(QuestMaster), typeof(QuestMasterTable), "quest_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("QuestId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("Name")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("RewardItemId")), - new MasterMemory.Meta.MetaProperty(typeof(QuestMaster).GetProperty("Cost")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(QuestMaster).GetProperty("QuestId"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/SampleTable.cs b/tests/MasterMemory.Tests/Generated/Tables/SampleTable.cs deleted file mode 100644 index a1b27b8..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/SampleTable.cs +++ /dev/null @@ -1,297 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SampleTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly Sample[] secondaryIndex1; - readonly Func secondaryIndex1Selector; - readonly Sample[] secondaryIndex2; - readonly Func secondaryIndex2Selector; - readonly Sample[] secondaryIndex3; - readonly Func secondaryIndex3Selector; - readonly Sample[] secondaryIndex5; - readonly Func secondaryIndex5Selector; - readonly Sample[] secondaryIndex6; - readonly Func secondaryIndex6Selector; - readonly Sample[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - readonly Sample[] secondaryIndex4; - readonly Func secondaryIndex4Selector; - - public SampleTable(Sample[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - this.secondaryIndex1Selector = x => (x.Id, x.Age, x.FirstName, x.LastName); - this.secondaryIndex1 = CloneAndSortBy(this.secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default); - this.secondaryIndex2Selector = x => (x.Id, x.Age); - this.secondaryIndex2 = CloneAndSortBy(this.secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default); - this.secondaryIndex3Selector = x => (x.Id, x.Age, x.FirstName); - this.secondaryIndex3 = CloneAndSortBy(this.secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default); - this.secondaryIndex5Selector = x => x.Age; - this.secondaryIndex5 = CloneAndSortBy(this.secondaryIndex5Selector, System.Collections.Generic.Comparer.Default); - this.secondaryIndex6Selector = x => (x.FirstName, x.Age); - this.secondaryIndex6 = CloneAndSortBy(this.secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default); - this.secondaryIndex0Selector = x => (x.FirstName, x.LastName); - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default); - this.secondaryIndex4Selector = x => x.FirstName; - this.secondaryIndex4 = CloneAndSortBy(this.secondaryIndex4Selector, System.StringComparer.Ordinal); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByIdAndAgeAndFirstNameAndLastName => new RangeView(secondaryIndex1, 0, secondaryIndex1.Length - 1, true); - public RangeView SortByIdAndAge => new RangeView(secondaryIndex2, 0, secondaryIndex2.Length - 1, true); - public RangeView SortByIdAndAgeAndFirstName => new RangeView(secondaryIndex3, 0, secondaryIndex3.Length - 1, true); - public RangeView SortByAge => new RangeView(secondaryIndex5, 0, secondaryIndex5.Length - 1, true); - public RangeView SortByFirstNameAndAge => new RangeView(secondaryIndex6, 0, secondaryIndex6.Length - 1, true); - public RangeView SortByFirstNameAndLastName => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - public RangeView SortByFirstName => new RangeView(secondaryIndex4, 0, secondaryIndex4.Length - 1, true); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public Sample FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out Sample result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public Sample FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public Sample FindByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) key) - { - return FindUniqueCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, key, true); - } - - public bool TryFindByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, key, out result); - } - - public Sample FindClosestByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, key, selectLower); - } - - public RangeView FindRangeByIdAndAgeAndFirstNameAndLastName((int Id, int Age, string FirstName, string LastName) min, (int Id, int Age, string FirstName, string LastName) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex1, secondaryIndex1Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default, min, max, ascendant); - } - - public Sample FindByIdAndAge((int Id, int Age) key) - { - return FindUniqueCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, key, true); - } - - public bool TryFindByIdAndAge((int Id, int Age) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, key, out result); - } - - public Sample FindClosestByIdAndAge((int Id, int Age) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, key, selectLower); - } - - public RangeView FindRangeByIdAndAge((int Id, int Age) min, (int Id, int Age) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex2, secondaryIndex2Selector, System.Collections.Generic.Comparer<(int Id, int Age)>.Default, min, max, ascendant); - } - - public Sample FindByIdAndAgeAndFirstName((int Id, int Age, string FirstName) key) - { - return FindUniqueCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, key, true); - } - - public bool TryFindByIdAndAgeAndFirstName((int Id, int Age, string FirstName) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, key, out result); - } - - public Sample FindClosestByIdAndAgeAndFirstName((int Id, int Age, string FirstName) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, key, selectLower); - } - - public RangeView FindRangeByIdAndAgeAndFirstName((int Id, int Age, string FirstName) min, (int Id, int Age, string FirstName) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex3, secondaryIndex3Selector, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default, min, max, ascendant); - } - - public RangeView FindByAge(int key) - { - return FindManyCore(secondaryIndex5, secondaryIndex5Selector, System.Collections.Generic.Comparer.Default, key); - } - - public RangeView FindClosestByAge(int key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex5, secondaryIndex5Selector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByAge(int min, int max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex5, secondaryIndex5Selector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public RangeView FindByFirstNameAndAge((string FirstName, int Age) key) - { - return FindManyCore(secondaryIndex6, secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default, key); - } - - public RangeView FindClosestByFirstNameAndAge((string FirstName, int Age) key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex6, secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default, key, selectLower); - } - - public RangeView FindRangeByFirstNameAndAge((string FirstName, int Age) min, (string FirstName, int Age) max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex6, secondaryIndex6Selector, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default, min, max, ascendant); - } - - public Sample FindByFirstNameAndLastName((string FirstName, string LastName) key) - { - return FindUniqueCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, true); - } - - public bool TryFindByFirstNameAndLastName((string FirstName, string LastName) key, out Sample result) - { - return TryFindUniqueCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, out result); - } - - public Sample FindClosestByFirstNameAndLastName((string FirstName, string LastName) key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, key, selectLower); - } - - public RangeView FindRangeByFirstNameAndLastName((string FirstName, string LastName) min, (string FirstName, string LastName) max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default, min, max, ascendant); - } - - public RangeView FindByFirstName(string key) - { - return FindManyCore(secondaryIndex4, secondaryIndex4Selector, System.StringComparer.Ordinal, key); - } - - public RangeView FindClosestByFirstName(string key, bool selectLower = true) - { - return FindManyClosestCore(secondaryIndex4, secondaryIndex4Selector, System.StringComparer.Ordinal, key, selectLower); - } - - public RangeView FindRangeByFirstName(string min, string max, bool ascendant = true) - { - return FindManyRangeCore(secondaryIndex4, secondaryIndex4Selector, System.StringComparer.Ordinal, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - ValidateUniqueCore(secondaryIndex1, secondaryIndex1Selector, "(Id, Age, FirstName, LastName)", resultSet); - ValidateUniqueCore(secondaryIndex2, secondaryIndex2Selector, "(Id, Age)", resultSet); - ValidateUniqueCore(secondaryIndex3, secondaryIndex3Selector, "(Id, Age, FirstName)", resultSet); - ValidateUniqueCore(secondaryIndex0, secondaryIndex0Selector, "(FirstName, LastName)", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(Sample), typeof(SampleTable), "s_a_m_p_l_e", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("Id")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("Age")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("FirstName")), - new MasterMemory.Meta.MetaProperty(typeof(Sample).GetProperty("LastName")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - typeof(Sample).GetProperty("Age"), - typeof(Sample).GetProperty("FirstName"), - typeof(Sample).GetProperty("LastName"), - }, false, true, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName, string LastName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - typeof(Sample).GetProperty("Age"), - }, false, true, System.Collections.Generic.Comparer<(int Id, int Age)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Id"), - typeof(Sample).GetProperty("Age"), - typeof(Sample).GetProperty("FirstName"), - }, false, true, System.Collections.Generic.Comparer<(int Id, int Age, string FirstName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("Age"), - }, false, false, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("FirstName"), - typeof(Sample).GetProperty("Age"), - }, false, false, System.Collections.Generic.Comparer<(string FirstName, int Age)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("FirstName"), - typeof(Sample).GetProperty("LastName"), - }, false, true, System.Collections.Generic.Comparer<(string FirstName, string LastName)>.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(Sample).GetProperty("FirstName"), - }, false, false, System.StringComparer.Ordinal), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/SequentialCheckMasterTable.cs b/tests/MasterMemory.Tests/Generated/Tables/SequentialCheckMasterTable.cs deleted file mode 100644 index 42dc0e7..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/SequentialCheckMasterTable.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SequentialCheckMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public SequentialCheckMasterTable(SequentialCheckMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public SequentialCheckMaster FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out SequentialCheckMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public SequentialCheckMaster FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(SequentialCheckMaster), typeof(SequentialCheckMasterTable), "sequantial_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(SequentialCheckMaster).GetProperty("Id")), - new MasterMemory.Meta.MetaProperty(typeof(SequentialCheckMaster).GetProperty("Cost")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(SequentialCheckMaster).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/SingleMasterTable.cs b/tests/MasterMemory.Tests/Generated/Tables/SingleMasterTable.cs deleted file mode 100644 index b428cde..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/SingleMasterTable.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SingleMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public SingleMasterTable(SingleMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Id; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public SingleMaster FindById(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindById(int key, out SingleMaster result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Id; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public SingleMaster FindClosestById(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeById(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Id", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(SingleMaster), typeof(SingleMasterTable), "single_master", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(SingleMaster).GetProperty("Id")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(SingleMaster).GetProperty("Id"), - }, true, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/SkillMasterTable.cs b/tests/MasterMemory.Tests/Generated/Tables/SkillMasterTable.cs deleted file mode 100644 index aa6f57b..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/SkillMasterTable.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class SkillMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public SkillMasterTable(SkillMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => (x.SkillId, x.SkillLevel); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - public SkillMaster FindBySkillIdAndSkillLevel((int SkillId, int SkillLevel) key) - { - return FindUniqueCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, key, true); - } - - public bool TryFindBySkillIdAndSkillLevel((int SkillId, int SkillLevel) key, out SkillMaster result) - { - return TryFindUniqueCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, key, out result); - } - - public SkillMaster FindClosestBySkillIdAndSkillLevel((int SkillId, int SkillLevel) key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, key, selectLower); - } - - public RangeView FindRangeBySkillIdAndSkillLevel((int SkillId, int SkillLevel) min, (int SkillId, int SkillLevel) max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "(SkillId, SkillLevel)", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(SkillMaster), typeof(SkillMasterTable), "skillmaster", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("SkillId")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("SkillLevel")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("AttackPower")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("SkillName")), - new MasterMemory.Meta.MetaProperty(typeof(SkillMaster).GetProperty("Description")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(SkillMaster).GetProperty("SkillId"), - typeof(SkillMaster).GetProperty("SkillLevel"), - }, true, true, System.Collections.Generic.Comparer<(int SkillId, int SkillLevel)>.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/TestMasterTable.cs b/tests/MasterMemory.Tests/Generated/Tables/TestMasterTable.cs deleted file mode 100644 index e21474c..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/TestMasterTable.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests.TestStructures; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System.Text; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class TestMasterTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - - public TestMasterTable(TestMaster[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.TestID; - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - - public RangeView FindByTestID(int key) - { - return FindManyCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key); - } - - public RangeView FindClosestByTestID(int key, bool selectLower = true) - { - return FindManyClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByTestID(int min, int max, bool ascendant = true) - { - return FindManyRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(TestMaster), typeof(TestMasterTable), "TestMaster", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(TestMaster).GetProperty("TestID")), - new MasterMemory.Meta.MetaProperty(typeof(TestMaster).GetProperty("Value")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(TestMaster).GetProperty("TestID"), - }, true, false, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/Generated/Tables/UserLevelTable.cs b/tests/MasterMemory.Tests/Generated/Tables/UserLevelTable.cs deleted file mode 100644 index a37d5ac..0000000 --- a/tests/MasterMemory.Tests/Generated/Tables/UserLevelTable.cs +++ /dev/null @@ -1,131 +0,0 @@ -// -#pragma warning disable CS0105 -using MasterMemory.Tests; -using MasterMemory.Validation; -using MasterMemory; -using MessagePack; -using System.Collections.Generic; -using System; - -namespace MasterMemory.Tests.Tables -{ - public sealed partial class UserLevelTable : TableBase, ITableUniqueValidate - { - public Func PrimaryKeySelector => primaryIndexSelector; - readonly Func primaryIndexSelector; - - readonly UserLevel[] secondaryIndex0; - readonly Func secondaryIndex0Selector; - - public UserLevelTable(UserLevel[] sortedData) - : base(sortedData) - { - this.primaryIndexSelector = x => x.Level; - this.secondaryIndex0Selector = x => x.Exp; - this.secondaryIndex0 = CloneAndSortBy(this.secondaryIndex0Selector, System.Collections.Generic.Comparer.Default); - OnAfterConstruct(); - } - - partial void OnAfterConstruct(); - - public RangeView SortByExp => new RangeView(secondaryIndex0, 0, secondaryIndex0.Length - 1, true); - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public UserLevel FindByLevel(int key) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Level; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { return data[mid]; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - return ThrowKeyNotFound(key); - } - - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - public bool TryFindByLevel(int key, out UserLevel result) - { - var lo = 0; - var hi = data.Length - 1; - while (lo <= hi) - { - var mid = (int)(((uint)hi + (uint)lo) >> 1); - var selected = data[mid].Level; - var found = (selected < key) ? -1 : (selected > key) ? 1 : 0; - if (found == 0) { result = data[mid]; return true; } - if (found < 0) { lo = mid + 1; } - else { hi = mid - 1; } - } - result = default; - return false; - } - - public UserLevel FindClosestByLevel(int key, bool selectLower = true) - { - return FindUniqueClosestCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByLevel(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(data, primaryIndexSelector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - public UserLevel FindByExp(int key) - { - return FindUniqueCoreInt(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, true); - } - - public bool TryFindByExp(int key, out UserLevel result) - { - return TryFindUniqueCoreInt(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, out result); - } - - public UserLevel FindClosestByExp(int key, bool selectLower = true) - { - return FindUniqueClosestCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, key, selectLower); - } - - public RangeView FindRangeByExp(int min, int max, bool ascendant = true) - { - return FindUniqueRangeCore(secondaryIndex0, secondaryIndex0Selector, System.Collections.Generic.Comparer.Default, min, max, ascendant); - } - - - void ITableUniqueValidate.ValidateUnique(ValidateResult resultSet) - { -#if !DISABLE_MASTERMEMORY_VALIDATOR - - ValidateUniqueCore(data, primaryIndexSelector, "Level", resultSet); - ValidateUniqueCore(secondaryIndex0, secondaryIndex0Selector, "Exp", resultSet); - -#endif - } - -#if !DISABLE_MASTERMEMORY_METADATABASE - - public static MasterMemory.Meta.MetaTable CreateMetaTable() - { - return new MasterMemory.Meta.MetaTable(typeof(UserLevel), typeof(UserLevelTable), "UserLevel", - new MasterMemory.Meta.MetaProperty[] - { - new MasterMemory.Meta.MetaProperty(typeof(UserLevel).GetProperty("Level")), - new MasterMemory.Meta.MetaProperty(typeof(UserLevel).GetProperty("Exp")), - }, - new MasterMemory.Meta.MetaIndex[]{ - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(UserLevel).GetProperty("Level"), - }, true, true, System.Collections.Generic.Comparer.Default), - new MasterMemory.Meta.MetaIndex(new System.Reflection.PropertyInfo[] { - typeof(UserLevel).GetProperty("Exp"), - }, false, true, System.Collections.Generic.Comparer.Default), - }); - } - -#endif - } -} \ No newline at end of file diff --git a/tests/MasterMemory.Tests/MasterMemory.Tests.csproj b/tests/MasterMemory.Tests/MasterMemory.Tests.csproj index de4c278..518be7e 100644 --- a/tests/MasterMemory.Tests/MasterMemory.Tests.csproj +++ b/tests/MasterMemory.Tests/MasterMemory.Tests.csproj @@ -1,26 +1,28 @@  - net6.0 + net9.0 false + - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + + + Analyzer + false + - - + + + - + diff --git a/tests/MasterMemory.Tests/MessagePackResolver.cs b/tests/MasterMemory.Tests/MessagePackResolver.cs index d223ace..c5ee264 100644 --- a/tests/MasterMemory.Tests/MessagePackResolver.cs +++ b/tests/MasterMemory.Tests/MessagePackResolver.cs @@ -1,26 +1,7 @@ using MessagePack; -using MessagePack.Formatters; using MessagePack.Resolvers; -using System; -using System.Collections.Generic; -using System.Text; -namespace MasterMemory.Tests -{ - public class MessagePackResolver : IFormatterResolver - { - public static IFormatterResolver Instance = new MessagePackResolver(); +namespace MasterMemory.Tests; - MessagePackResolver() - { - - } - - public IMessagePackFormatter GetFormatter() - { - return MasterMemoryResolver.Instance.GetFormatter() - ?? GeneratedResolver.Instance.GetFormatter() - ?? StandardResolver.Instance.GetFormatter(); - } - } -} +[CompositeResolver(typeof(MasterMemoryResolver), typeof(StandardResolver))] +public partial class MessagePackResolver; \ No newline at end of file